Search code examples
iosobjective-cnsstringnsrange

How to get all NSRange of a particular character in a NSString?


I have two NSStrings: orgText and searchLetter.
I want to highlight every occurrences of the searchLetter in the orgText with a red color.
How can I get the NSRange of all occurrences of the searchLetter ?
for eg :

suppose: orgText = "abcahaiapaoiuiapplma"
         searchLetter = "a".

I want to hightlight all "a" occurrences in "abcahaiapaoiuiapplma" with red color.
Thanks.


Solution

  • I wrote this method for my project - SUITextView with highlight:

    - (NSMutableAttributedString*) setColor:(UIColor*)color word:(NSString*)word inText:(NSMutableAttributedString*)mutableAttributedString {
    
        NSUInteger count = 0, length = [mutableAttributedString length];
        NSRange range = NSMakeRange(0, length);
    
        while(range.location != NSNotFound)
        {
            range = [[mutableAttributedString string] rangeOfString:word options:0 range:range];
            if(range.location != NSNotFound) {
                [mutableAttributedString setTextColor:color range:NSMakeRange(range.location, [word length])];
                range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
                count++; 
            }
        }
    
        return mutableAttributedString;
    }
    

    And in my category of NSMutableAttributedString:

    - (void) setTextColor:(UIColor*)color range:(NSRange)range {
        // kCTForegroundColorAttributeName
        [self removeAttribute:(NSString*)kCTForegroundColorAttributeName range:range]; // Work around for Apple leak
        [self addAttribute:(NSString*)kCTForegroundColorAttributeName value:(id)color.CGColor range:range];
    }