如何在NSString中获取子字符串的NSRange? [英] How to get NSRange(s) for a substring in NSString?
本文介绍了如何在NSString中获取子字符串的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...";
如何循环使用此NSString并为每次加利福尼亚事件获取NSRange,我希望NSRange因为我想在NSAttributed字符串中更改它的颜色。
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];
}
}
推荐答案
很多解决这个问题的方法 - NSScanner
被提及; rangeOfString:options:range
等。为了完整起见,我将提到 NSRegularExpression
。这也有效:
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];
}];
这篇关于如何在NSString中获取子字符串的NSRange?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文