您可以隨時使用'rangeOfString:options:range:'作爲第二個(從第一個'location'之後開始)。
選項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);
}
}
好吧,它工作正常,但這到底是什麼:'@「([\」])(?:\\\\\ 1 |。)*?\\ 1「'?? – Snowman
@mohabitar這是一個[正則表達式](http://en.wikipedia.org/wiki/Regular_expression)我建議閱讀它們,它們非常強大和有用。(另外,[NSRegularExpression]的鏈接指向Apple文檔(https:// developer.apple.com/library/mac/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html)) –
另外請注意,它大多看起來非常可怕,因爲我不得不逃脫一些字符(每個\和「)。 – JustSid