iphone - 在 NSString 中查找子字符串的所有位置(不仅仅是第一个)

标签 iphone ios xcode nsstring substring

有一个子串在一个字符串中多次出现。我用的是rangeOfString,但是好像只能找到第一个位置。如何找到子字符串的所有位置?

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: 并将第三个参数设置为超出第一次出现的范围。例如,您可以这样做:

NSRange searchRange = NSMakeRange(0,string.length);
NSRange foundRange;
while (searchRange.location < string.length) {
    searchRange.length = string.length-searchRange.location;
    foundRange = [string rangeOfString:substring options:0 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;
    }
}

关于iphone - 在 NSString 中查找子字符串的所有位置(不仅仅是第一个),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7033574/

相关文章:

ios - 我可以忽略 "Unable to simultaneously satisfy constraints"吗?

ios - 无法调用非函数类型的值

ios:onclick tableviewcell 如果 nsuserdefaults 存在转到 View Controller ,否则转到另一个 View Controller

ios - showViewController 不工作

ios - 环球银行金融电信协会 : UITableView passing all cell's data(TextField & Label) to UIViewController

ios - UIKeyboardWillShow 通知在物理设备上调用了两次,但在模拟器中没有调用

ios - mkannotation View 中的按钮操作不起作用?

ios - 本地通知不会出现 - iOS

iphone - 添加到可变数组的对象数量不正确

ios - 核心数据 : filter many to may relationship with NSPredicate