如何获得NSString的子string的NSRange(s)?

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,因为我想改变它在NSAttributedstring中的颜色。

  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 。 这也适用:

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

 [str rangeOfString:@"California"] 

 [str rangeOfString:@"California" options:YOUR_OPTIONS range:rangeToSearch] 

你可以使用rangeOfString:options:range:或者NSScanner(还有其他的可能性,比如正则expression式,但是无论如何)。 使用第一种方法更新范围比较容易,即search第一次出现,然后根据结果更新search范围。 当search范围为空时,您已经find了一切;