从NSString中的某个字符获取子字符串

时间:2010-06-16 09:10:15

标签: iphone objective-c nsstring

如果我最初有一个NSString:

"ABCDE*FGHI"

如何让它变成

"FGHI"

换句话说,从星号开始的所有内容都会保留。

同样,我将如何将其变为:

"ABCDE"

(保留星号的所有内容)

由于

4 个答案:

答案 0 :(得分:63)

NSString *myString = @"ABCDE*FGHI"; 
NSArray *myArray = [myString componentsSeparatedByString:@"*"];
  • myArray的密钥0将包含@“ABCDE”
  • 键1将包含@“FGHI”

如果您想要多个字符作为分隔符,
使用componentsSeparatedByCharactersInSet

NSString *myString = @"ABCDE*FGHI-JKL"; 
NSArray *myArray = [myString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"*-"]];
  • myArray的密钥0将包含@“ABCDE”
  • 键1将包含@“FGHI”
  • 键2将包含@“JKL”

答案 1 :(得分:22)

NSString *myString = @"ABCDE*FGHI";
NSString *subString = [myString substringWithRange: NSMakeRange(0, [myString rangeOfString: @"*"].location)];

答案 2 :(得分:9)

NSString *myString = @"ABCDE*FGHI";
NSArray *myArray = [myString componentsSeparatedByString:@"*"];

答案 3 :(得分:0)

NSString *yourString = @"ABCDE*FGHI";

NSMutableArray * array = [[NSMutableArray alloc] initWithArray:[yourString componentsSeparatedByString:@"*"]];

for(int i =0 ; i < array.count ; i++){
    NSLog(@"- %d : %@ \n",i,[array objectAtIndex:i]);
}