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

后端 未结 6 1840
广开言路
广开言路 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 04:30

    I suggest using regular expression because it's a more declarative way and has fewer lines of code to write.

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"%@" options:nil error:nil];
    NSString *toSearchStr = @"12312 %@ Text %@ asdsa %@";
    __block int occurs = 0;
    [regex enumerateMatchesInString:toSearchStr options:0 range:NSMakeRange(0, toSearchStr.length) usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
           occurs++;
    }];
    // occurs == 3
    

提交回复
热议问题