如何在@“;”之前分隔第一个字符串在数组?

时间:2011-09-22 14:39:43

标签: objective-c

我想在数组中分割一个字符串:

NSString *test = @"How are you;<random>[Good;Bad]";
NSArray *howareyou = [test componentsSeparatedByString:@";"]

然后它会拆分<random>[GoodBad] ...

我只想分开How are you<random>[Good;Bad]

我该怎么做?

2 个答案:

答案 0 :(得分:4)

NSString *test = @"How are you;<random>[Good;Bad]"; 
NSRange colonRange = [test rangeOfString:@";"];
if (colonRange.location != NSNotFound){
    NSString *firstHalf = [test substringToIndex:colonRange.location];
    NSString *secondHalf = [test substringFromIndex:NSMaxRange(colonRange)];
    NSLog(@"%@ - %@", firstHalf, secondHalf);
}else{
    NSLog(@"No luck");
}

答案 1 :(得分:0)

NSString *test = @"How are you;<random>[Good;Bad]";
NSArray *howareyou = [test componentsSeparatedByString:@";"];

NSString *desired = [howareyou objectAtIndex:0];
NSString *rest = [[howareyou subarrayWithRange:NSMakeRange(1, [howareyou count]-1)]
                        componentsJoinedByString:@";"];

没有那么低效(或脆弱 - 没有错误检查,范围检查,长度检查等......)。这里和那里有一些长度有限的字符串非常精细,对于大输入等可能是不可接受的。

先测量。优化之后。