How to get NSRange(s) for a substring in NSString? [duplicate]

陌路散爱 提交于 2019-12-03 00:49:19
FluffulousChimp

Lots of ways of solving this problem - NSScanner was mentioned; rangeOfString:options:range etc. For completeness' sake, I'll mention NSRegularExpression. This also works:

    NSMutableAttributedString *mutableString = nil;
    NSString *sampleText = @"I live in California, blah blah blah California.";
    mutableString = [[NSMutableAttributedString alloc] initWithString:sampleText];

    NSString *pattern = @"(California)";
    NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];

    //  enumerate matches
    NSRange range = NSMakeRange(0,[sampleText length]);
    [expression enumerateMatchesInString:sampleText options:0 range:range usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
        NSRange californiaRange = [result rangeAtIndex:0];
        [mutableString addAttribute:NSForegroundColorAttributeName value:[NSColor greenColor] range:californiaRange];
    }];

with

[str rangeOfString:@"California"]

and

[str rangeOfString:@"California" options:YOUR_OPTIONS range:rangeToSearch]

You may use rangeOfString:options:range: or NSScanner (there are other possibilities like regexps but anyway). It's easier to use first approach updating range, i.e. search for first occurrence and then depending on the result update the search range. When the search range is empty, you've found everything;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!