Find all locations of substring in NSString (not just first)

后端 未结 6 1837
广开言路
广开言路 2020-11-30 04:12

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 l

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-30 04:32

    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: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;
        }
    }
    

提交回复
热议问题