您始终可以将“rangeOfString:options:range:”用于第二个(从第一个的“位置”开始)。
选项1
- (NSRange)rangeOfQuoteInString:(NSString *)str {
int firstMatch = [str rangeOfString:@"\""].location;
int secondMatch = [str rangeOfString:@"\"" options:0 range:NSMakeRange(firstMatch + 1, [str length] - firstMatch - 1)].location;
return NSMakeRange(firstMatch, secondMatch + 1 - firstMatch);
}
我希望这是正确的。晚餐时在我的手机上完成的。;-)
但是,另一件事是,由于字符串范围可能会执行类似的实现,为什么不迭代字符串中的“char”值并查找匹配项#1 和#2?可能一样快或更快。
选项 2
- (NSRange)rangeOfQuoteInString:(NSString *)str {
int firstMatch = -1;
int secondMatch = -1;
for (int i = 0; i < [str length]; i = i + 1) {
unichar c = [str characterAtIndex:i];
if (c == '"') {
if (firstMatch == -1) {
firstMatch = i;
} else {
secondMatch = i;
break;
}
}
}
if (firstMatch == -1 || secondMatch == -1) {
// No full quote was found
return NSMakeRange(NSNotFound, 0);
} else {
return NSMakeRange(firstMatch, secondMatch + 1 - firstMatch);
}
}