我想为NSRange
中的每个组获得NSString
,以空格分隔。
我目前有这个:
self.statement1String = [NSString stringWithFormat:@"??? = n1 + n2 + n3 + n4"];
for (NSString *component in [self.statement1String componentsSeparatedByString:@" "])
{
NSRange range=[self.statement1String rangeOfString:component];
NSLog(@"range is %@ for string %@", [NSValue valueWithRange:range], component);
}
打印出来
2014-11-12 17:19:00.011[3606:758370] range is NSRange: {0, 3} for string ???
2014-11-12 17:19:00.012[3606:758370] range is NSRange: {4, 1} for string =
2014-11-12 17:19:00.012[3606:758370] range is NSRange: {6, 2} for string n1
2014-11-12 17:19:00.013[3606:758370] range is NSRange: {9, 1} for string +
2014-11-12 17:19:00.013[3606:758370] range is NSRange: {11, 2} for string n2
2014-11-12 17:19:00.014[3606:758370] range is NSRange: {9, 1} for string +
2014-11-12 17:19:00.015[3606:758370] range is NSRange: {16, 2} for string n3
2014-11-12 17:19:00.015[3606:758370] range is NSRange: {9, 1} for string +
2014-11-12 17:19:00.015[3606:758370] range is NSRange: {21, 2} for string n4
我得到了相同的范围' +'在每次迭代中。我怎样才能确保我得到下一个' +'登录for循环?
答案 0 :(得分:4)
您可以使用-rangeOfString:options:range:
,将包含最后一个范围结尾的范围传递给字符串的结尾。
但是,这是一项更适合NSScanner
的工作。
答案 1 :(得分:2)
改为使用rangeOfString:options:range:
。
self.statement1String = @"??? = n1 + n2 + n3 + n4";
NSInteger start = 0;
for (NSString *component in [self.statement1String componentsSeparatedByString:@" "]) {
NSRange checkRange = NSMakeRange(start, self.statementString.length - start);
NSRange range = [self.statement1String rangeOfString:component options:0 range:checkRange];
NSLog(@"range is %@ for string %@", NSStringFromRange(range), component);
start = range.location + range.length;
}