2012-08-29 33 views
0

我從過去幾個小時使用了NSSting操作方法。並發現很多像這樣的堆棧溢出here在NSString中出現一個字符

我有一個字符串「1800 Ellis St,San Francisco,CA 94102,USA」。字符串可能有任何數量的「,」。 「,」之後我必須拿下倒數第三(San Franncisco)和最後一個(USA)子串。

和輸出應該是「San Franncisco USA」。

我有邏輯如何做到這一點在我的腦海裏,但我努力實現它。

我試着用這個代碼獲取字符串中最後三個「,」的位置。但它不是爲我工作

NSInteger commaArr[3]; 

     int index=0; 
     int commaCount=0; 

     for(unsigned int i = [strGetCityName length]; i > 0; i--) 
     { 
      if([strGetCityName characterAtIndex:i] == ',') 
      { 

       commaArr[index]=i; 
       index++; 
       ++commaCount; 
       if(commaCount == 3) 
       { 
        break; 
       } 
      } 
     } 

感謝

回答

2

你可以這樣說:

NSString *s = @"1800 Ellis St, San Francisco, CA 94102, USA"; 
NSArray *parts = [s componentsSeparatedByString:@","]; 
NSUInteger len = [parts count]; 
NSString *res; 
if (len >= 3) { 
    res = [NSString stringWithFormat:@"%@%@", [parts objectAtIndex:len-3], [parts objectAtIndex:len-1]]; 
} else { 
    res = @"ERROR: Not enough parts!"; 
} 

componentsSeparatedByString:將在,分割字符串,並stringWithFormat:將把部分重新走到一起。

+0

感謝快速回復..我的問題解決了:) – QueueOverFlow

0

試試這個:

NSString *string = @"1800 Ellis St, San Francisco, CA 94102, USA"; 
NSArray *components = [string componentsSeparatedByString:@","]; 
NSString *sanFrancisco = [components objectAtIndex:components.count - 3]; 
NSString *usa = [components objectAtIndex:components.count - 1]; 
NSString *result = [sanFrancisco stringByAppendingString:usa]; 
1
NSString *s = @"1800 Ellis St, San Francisco, CA 94102, USA"; 
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^(?:[^,]*,)?\\s*([^,]*),\\s*(?:[^,]*),\\s*([^,]*)$" options:0 error:NULL]; 
NSString *result = [regex stringByReplacingMatchesInString:s options:0 range:NSMakeRange(0, [s length]) withTemplate:@"'$1 $2'"];