在NSString中查找子字符串的所有位置(不仅仅是第一个) [英] Find all locations of substring in NSString (not just first)
本文介绍了在NSString中查找子字符串的所有位置(不仅仅是第一个)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
字符串中有一个子字符串多次出现。我使用 rangeOfString
,但它似乎只能找到第一个位置。如何查找子字符串的所有位置?
There is a substring that occurs in a string several times. I use rangeOfString
, but it seems that it can only find the first location. How can I find all the locations of the substring?
NSString *subString1 = @"</content>";
NSString *subString2 = @"--\n";
NSRange range1 = [newresults rangeOfString:subString1];
NSRange range2 = [newresults rangeOfString:subString2];
int location1 = range1.location;
int location2 = range2.location;
NSLog(@"%i",location1);
NSLog(@"%i",location2);
推荐答案
您可以使用 rangeOfString: options:range:
并将第三个参数设置为超出第一个参数的范围。例如,你可以这样做:
You can use rangeOfString:options:range:
and set the third argument to be beyond the range of the first occurrence. For example, you can do something like this:
NSRange searchRange = NSMakeRange(0,string.length);
NSRange foundRange;
while (searchRange.location < string.length) {
searchRange.length = string.length-searchRange.location;
foundRange = [string rangeOfString:substring options:nil range:searchRange];
if (foundRange.location != NSNotFound) {
// found an occurrence of the substring! do stuff here
searchRange.location = foundRange.location+foundRange.length;
} else {
// no more substring to find
break;
}
}
这篇关于在NSString中查找子字符串的所有位置(不仅仅是第一个)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文