0

我对componentsSeparatedByString:给我奇怪的结果有疑问。

使用此代码:

CCLOG(@"    Found string %@",string);
tokens = [string componentsSeparatedByString:@"[,]"];

CCLOG(@"    sanity %@", (NSString *)[tokens objectAtIndex:0]);
int type = [(NSString *)[tokens objectAtIndex:0] integerValue];
int x = [(NSString *)[tokens objectAtIndex:1] integerValue]; //<< breakpoint

我得到这个输出日志:

2013-03-03 21:29:39.184 Legends[33427:c07]     Found string 1[0,5]
2013-03-03 21:29:39.185 Legends[33427:c07]     sanity 1[0,5]

所以程序在最后一行中断是有道理的,因为数组标记中的第一个对象具有整个字符串,但不应该将字符串@"1[0,5]"拆分为@"1" @"0"and@"5"吗?

4

1 回答 1

2

不,您误解了该方法的工作原理。componentsSeparatedByString:不使用传递字符串中的单个字符,它使用整个字符串。您的分隔符是三个字符的序列[,]。类似的字符串@"pecan[,]pie"使用此分隔符,但@"1[0,5]"不使用。类似的方法componentsSeparatedByCharactersInSet:会做你所期望的:

[string componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"[,]"]];

如果您想从字符串中提取数字并获取它们的数值,您可能需要查看NSScanner.

于 2013-03-04T02:45:34.460 回答