Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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...";

How can I loop through this NSString and get NSRange for each occurrence of "California", I want the NSRange because I would like to change it's color in the NSAttributed string.

 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];
    }
}
like image 667
SMA2012 Avatar asked Nov 27 '22 20:11

SMA2012


2 Answers

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];
    }];
like image 95
FluffulousChimp Avatar answered Dec 19 '22 13:12

FluffulousChimp


with

[str rangeOfString:@"California"]

and

[str rangeOfString:@"California" options:YOUR_OPTIONS range:rangeToSearch]
like image 39
tkanzakic Avatar answered Dec 19 '22 11:12

tkanzakic