2011-04-11 41 views
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]; 
} 

回答

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]]; 

這將進行現場標識符的轉換(但應做一些錯誤的情況下檢查無論是前綴還是後綴都保持無)。

打造字段名的列表將它們添加到一個的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; 
+0

某些就像creationTSZ一個字符串,顯然無法解析多個駱駝案件如thisStringHasAnotherCapitalLetter 。將嘗試與NSScanner合作,看看我是否能夠實現這一目標。感謝您指點我正確的方向。 – Devraj 2011-04-13 00:41:51