如何获取NSString中的特定字符的所有NSRange?

我有两个NSString: orgTextsearchLetter
我想用红色突出显示orgText中orgText每一个出现。
我怎样才能得到所有searchLetter
例如:

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

我想在红色的“abcahaiapaoiuiapplma”中突出所有“a”事件。
谢谢。

我为我的项目编写了这个方法 – SUITextView突出显示 :

 - (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; } 

并在我的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]; } 

我没有看到任何正则expression式的解决scheme,所以我创build了一个优雅的解决scheme,可能对未来的某个人有用。

 - (BOOL)highlightString:(NSString *)string inText:(NSMutableAttributedString *)attributedString withColour:(UIColor *)color { NSError *_error; NSRegularExpression *_regexp = [NSRegularExpression regularExpressionWithPattern:string options:NSRegularExpressionCaseInsensitive error:&_error]; if (_error == nil) { [_regexp enumerateMatchesInString:attributedString.string options:NSMatchingReportProgress range:NSMakeRange(0, attributedString.string.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { if (result.numberOfRanges > 0) { for (int i = 0; i < result.numberOfRanges; i++) { [attributedString addAttribute:NSBackgroundColorAttributeName value:color range:[result rangeAtIndex:i]]; } } }]; return TRUE; } else { return FALSE; } } 

代码在“setTextColor”为MutableAttributeString崩溃

而不是使用下面的代码

 NSDictionary *tempdict=[NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:12.0],NSFontAttributeName,color,NSForegroundColorAttributeName, nil]; [mutableAttributedString setAttributes:tempdict range:NSMakeRange(range.location, [word length])]; 

这是一个更简单的方法

 NSString *str = @"hello world"; NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:str]; [attr addAttributes:@{NSForegroundColorAttributeName : [UIColor redColor]} range:[str rangeOfString:@"world"]];