ios 如何为 NSString 中的子字符串获取 NSRange(s)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13621245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get NSRange(s) for a substring in NSString?
提问by SMA2012
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...";
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.
我如何遍历这个 NSString 并为每次出现“加利福尼亚”获取 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];
}
}
回答by FluffulousChimp
Lots of ways of solving this problem - NSScanner
was mentioned; rangeOfString:options:range
etc. For completeness' sake, I'll mention NSRegularExpression
. This also works:
很多解决这个问题的方法 -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];
}];
回答by tkanzakic
with
和
[str rangeOfString:@"California"]
and
和
[str rangeOfString:@"California" options:YOUR_OPTIONS range:rangeToSearch]
回答by MANIAK_dobrii
You may use rangeOfString:options:range: or NSScanner (there are other possibilities like regexps but anyway). It's easier to use first approach updating range, i.e. search for first occurrence and then depending on the result update the search range. When the search range is empty, you've found everything;
您可以使用 rangeOfString:options:range: 或 NSScanner(还有其他可能性,例如正则表达式,但无论如何)。使用第一种方法更新范围更容易,即搜索第一次出现,然后根据结果更新搜索范围。当搜索范围为空时,您已找到所有内容;