请注意,如果您只使用子字符串,那么您还将匹配作为其他单词一部分的子字符串,例如第二段中“arises”中的“is”。根据您的描述,这不是您想要的,但我可能误读了它。
Core Foundation 提供了CFStringTokenizer
帮助跨不同语言环境做这些事情的方法。
下面的代码没有以任何方式优化:
NSString *para = @"What I am trying to do is using a Stepper in my View to underline every word in a sentence sequentially. But the problem arises when it finds the same word it has encountered before for it will underline the 1st occurrence of that word instead of the 2nd occurrence where the current location is.";
NSString *searchedWord = @"is";
NSUInteger selectedOccurrence = 2; // From your stepper, zero-based.
NSUInteger counter = NSNotFound;
NSRange selectedRange = NSMakeRange(NSNotFound, 0);
CFStringTokenizerRef tokenizer = CFStringTokenizerCreate (NULL,(CFStringRef)para,CFRangeMake(0, para.length),kCFStringTokenizerUnitWord,NULL);
CFStringTokenizerTokenType tokenType;
while ( (tokenType = CFStringTokenizerAdvanceToNextToken(tokenizer)) != kCFStringTokenizerTokenNone ) {
CFRange tokenRange = CFStringTokenizerGetCurrentTokenRange(tokenizer);
NSString *token = (__bridge_transfer NSString*)CFStringCreateWithSubstring(kCFAllocatorDefault, (CFStringRef)para, tokenRange);
if ( [token compare:searchedWord options:NSCaseInsensitiveSearch] == NSOrderedSame ) {
// An occurrence of the word is found!
counter = counter == NSNotFound ? 0 : counter + 1;
if ( counter == selectedOccurrence ) {
// We found the occurrence we were looking for
selectedRange = NSMakeRange(tokenRange.location, tokenRange.length);
break;
}
}
};
// If selectedRange is different from the initial {NSNotFound,0} then we found something
if ( ! NSEqualRanges(selectedRange, NSMakeRange(NSNotFound, 0)) ) {
// Highlight your word found at selectedRange
NSLog(@"Found at %@", NSStringFromRange(selectedRange));
}
else {
// Not found, clean up
NSLog(@"An occurence number %ld not found", selectedOccurrence);
}