我正在尝试编写一个用于字符串转换的泛型方法(目的是为RESTful应用编程接口编写一个解析器)。
消息的目的是转换字符串,如下所示
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];
}发布于 2011-04-11 20:25:07
假设您的标识符的结构如下
<lowercase-prefix><Uppercase-char-and-remainder>您可以使用:
NSScaner *scanner = [NSScanner scannerWithString:fieldName];
NSString *prefix = nil;
[scanner scanCharactersFromSet:[NSCharacterSet lowercaseLetterCharacterSet] intoString:&prefix];
NSString *suffix = nil;
[scanner scanCharactersFromSet:[NSCharacterSet letterCharacterSet] intoString:&suffix];
NSString *fieldNameString = [NSString stringWithFormat:@"%@_%@", prefix, [suffix lowercaseString]];这将执行字段标识符的转换(但您应该执行一些错误检查,以防前缀或后缀保持为空)。
构建fieldNames列表的最简单方法是将它们添加到NSMutableArray中,然后加入它们:
NSMutableArray *fields = [[NSMutableArray alloc] init];
for (NSString *fieldName in [self fieldList]) {
// code as above
[fields add:fieldNameString];
}
NSString *commaFields = [fields componentsJoinedByString:@","];
[fields release];
return commaFields;https://stackoverflow.com/questions/5620858
复制相似问题