2009-02-27 184 views

回答

207

您也可以使用NString的componentsSeparatedByString方法,通過子字符串拆分字符串。從文檔

實施例:

NSString *list = @"Norman, Stanley, Fletcher"; 
NSArray *listItems = [list componentsSeparatedByString:@", "]; 
+0

我可以拆分單獨標記不同的字符串嗎?例如@「A,B^C〜D」 – 2009-02-27 09:53:14

37

的NSString有這幾個方法:

[myString substringToIndex:index]; 
[myString substringFromIndex:index]; 
[myString substringWithRange:range]; 

檢查NSString的文檔的詳細信息。

0

我寫了一個小的方法在部分的規定量來分割字符串。 請注意,它只支持單個分隔符字符。但我認爲這是分割NSString的有效方法。

//split string into given number of parts 
-(NSArray*)splitString:(NSString*)string withDelimiter:(NSString*)delimiter inParts:(int)parts{ 
    NSMutableArray* array = [NSMutableArray array]; 

    NSUInteger len = [string length]; 
    unichar buffer[len+1]; 

    //put separator in buffer 
    unichar separator[1]; 
    [delimiter getCharacters:separator range:NSMakeRange(0, 1)]; 

    [string getCharacters:buffer range:NSMakeRange(0, len)]; 

    int startPosition = 0; 
    int length = 0; 
    for(int i = 0; i < len; i++) { 

     //if array is parts-1 and the character was found add it to array 
     if (buffer[i]==separator[0] && array.count < parts-1) { 
      if (length>0) { 
       [array addObject:[string substringWithRange:NSMakeRange(startPosition, length)]]; 

      } 

      startPosition += length+1; 
      length = 0; 

      if (array.count >= parts-1) { 
       break; 
      } 

     }else{ 
      length++; 
     } 

    } 

    //add the last part of the string to the array 
    [array addObject:[string substringFromIndex:startPosition]]; 

    return array; 
} 
相關問題