NSRange, Find a word within a paragraph getting wrong results
ios, nsattributedstring, nsrange, nsstring, objective-c
Solution
The problem is that
NSRange range=[self.textLabel.text rangeOfString:word];
finds the first occurrence of the word in the text. A better option is to enumerate the text by words:
-(void)setTextHighlited :(NSString *)txt{
NSString *text = self.textLabel.text;
NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:text];
[text enumerateSubstringsInRange:NSMakeRange(0, [text length])
options:NSStringEnumerationByWords usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
if ([substring isEqualToString:txt]) {
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:substringRange];
}
}];
self.textLabel.attributedText = string;
}
This method has more advantages, for example it will find a word even if it is enclosed in quotation marks or surrounded by punctuation.
Problem
Ive written a method to highlight a word within a paragraph by sending it an `NSString` of that word, it was working perfectly until i faced this scenario: When i have this text: Their mother has tried dressing them in other ... When I'm passing the word `other`, the word "m`other`" is being highlighted, also when I'm passing `in` i got "dress`in`g". Here is my code: ``` -(void)setTextHighlited :(NSString *)txt{ NSMutableAttributedString * string = [[NSMutableAttributedString alloc]initWithString:self.textLabel.text]; for (NSString *word in [self.textLabel.text componentsSeparatedByString:@" "]) { if ([word hasPrefix:txt]) { NSRange range=[self.textLabel.text rangeOfString:word]; [string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range]; } ``` I've tried to use rangeOfString:options: with all of its options, but still have the same problem. Please advice PS: This is the source of my code