0
我想寫一個字符串轉換的通用方法(目的是我正在編寫一個RESTful API的解析器)。複雜Objective-C字符串替換
該消息的目的是將字符串轉換如下
creationTSZ - > creation_tsz
用戶id - > USER_ID
消息句柄轉換用戶id - > 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];
}
某些就像creationTSZ一個字符串,顯然無法解析多個駱駝案件如thisStringHasAnotherCapitalLetter 。將嘗試與NSScanner合作,看看我是否能夠實現這一目標。感謝您指點我正確的方向。 – Devraj 2011-04-13 00:41:51