我正在尝试为String转换编写一个通用方法(目的是为RESTful API编写解析器)。
该消息旨在按如下方式转换字符串
creationTSZ - > creation_tsz
userId - > USER_ID
邮件处理转换userId - > user_id,目前无效地循环遍历字符串并更改部分。
尚未处理creationTSZ - > creation_tsz,我认为进一步循环是非常低效的,我想知道是否有更好的方法来做到这一点?
可能是正则表达式吗?
-(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];
}
答案 0 :(得分:1)
假设您的标识符的结构类似于
<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;