如何在NSString中获取子字符串的NSRange?

SMA*_*012 3 nsstring uitextview nsattributedstring ios nsrange

NSString *str = @" My name is Mike, I live in California and I work in Texas. Weather in California is nice but in Texas is too hot...";
Run Code Online (Sandbox Code Playgroud)

我怎样才能遍历这个NSString并为每次出现的"California"获取NSRange,我想要NSRange,因为我想在NSAttributed字符串中更改它的颜色.

 NSRange range = NSMakeRange(0,  _stringLength);
 while(range.location != NSNotFound)
 {
    range = [[attString string] rangeOfString: @"California" options:0 range:range];


    if(range.location != NSNotFound)
    {

        range = NSMakeRange(range.location + range.length,  _stringLength - (range.location + range.length));


        [attString addAttribute:NSForegroundColorAttributeName value:_green range:range];
    }
}
Run Code Online (Sandbox Code Playgroud)

Flu*_*imp 38

NSScanner提到了很多解决这个问题的方法.rangeOfString:options:range等等.为了完整起见,我会提到NSRegularExpression.这也有效:

    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];
    }];
Run Code Online (Sandbox Code Playgroud)


tka*_*kic 19

[str rangeOfString:@"California"]
Run Code Online (Sandbox Code Playgroud)

[str rangeOfString:@"California" options:YOUR_OPTIONS range:rangeToSearch]
Run Code Online (Sandbox Code Playgroud)