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并为每次出现的“California”获取NSRange,我想要NSRange,因为我想在NSAttributed字符串中更改它的颜色。
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];
}
}
答案 0 :(得分:38)
提到了很多解决这个问题的方法 - NSScanner
; rangeOfString:options:range
等。为了完整起见,我会提到NSRegularExpression
。这也有效:
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];
}];
答案 1 :(得分:19)
带
[str rangeOfString:@"California"]
和
[str rangeOfString:@"California" options:YOUR_OPTIONS range:rangeToSearch]
答案 2 :(得分:0)
您可以使用rangeOfString:options:range:或NSScanner(还有其他可能性,例如regexps但无论如何)。使用第一种方法更新范围更容易,即搜索第一次出现,然后根据结果更新搜索范围。当搜索范围为空时,您已找到所有内容;