Я пытаюсь написать универсальный метод для преобразования строк (целью является написание синтаксического анализатора для RESTful API).
Целью сообщения является преобразование строк следующим образом
creationTSZ -> creation_tsz
userId -> user_id
Сообщение обрабатывает преобразование userId -> user_id, в настоящее время неэффективно циклически перебирая строку и изменяя части.
Пока не обрабатывает creationTSZ-> creation_tsz, я думаю, что дальнейшее зацикливание очень неэффективно, и мне интересно, есть ли лучший способ сделать это?
Возможно, Regex?
-(NSString *)fieldsQueryString
{
NSArray *fieldNames = [self fieldList];
/* Final composed string sent to Etsy */
NSMutableString *fieldString = [[[NSMutableString alloc] init] autorelease];
/* Characters that we replace with _lowerCase */
NSArray *replaceableChars = [NSArray arrayWithObjects:
@"Q", @"W", @"E", @"R", @"T", @"Y", @"U", @"I", @"O", @"P",
@"A", @"S", @"D", @"F", @"G", @"H", @"J", @"K", @"L",
@"Z", @"X", @"C", @"V", @"B", @"N", @"M", nil];
/* Reusable pointer for string replacements */
NSMutableString *fieldNameString = nil;
/* Loop through the array returned by the filter and change the names */
for(NSString *fieldName in fieldNames) {
/* Loop if the field is to be omited */
if ([[self valueForKey:fieldName] boolValue] == NO) continue;
/* Otherwise change the name to a field and add it */
fieldNameString = [fieldName mutableCopy];
for(NSString *replaceableChar in replaceableChars) {
[fieldNameString replaceOccurrencesOfString:replaceableChar
withString:[NSString stringWithFormat:@"_%@", [replaceableChar lowercaseString]]
options:0
range:NSMakeRange(0, [fieldNameString length])];
}
[fieldString appendFormat:@"%@,", fieldNameString];
[fieldNameString release];
}
fieldNames = nil;
/* Return the string without the last comma */
return [fieldString substringToIndex:[fieldString length] - 1];
}