To enumerate the words in a string, you should use -[NSString enumerateSubstringsInRange:options:usingBlock:]
with NSStringEnumerationByWords
and NSStringEnumerationLocalized
. All of the other methods listed use a means of identifying words which may not be locale-appropriate or correspond to the system definition. For example, two words separated by a comma but not whitespace (e.g. "foo,bar") would not be treated as separate words by any of the other answers, but they are in Cocoa text views.
[aString enumerateSubstringsInRange:NSMakeRange(0, [aString length])
options:NSStringEnumerationByWords | NSStringEnumerationLocalized
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop){
if ([substring rangeOfString:@"ll" options:NSCaseInsensitiveSearch].location != NSNotFound)
/* do whatever */;
}];
As documented for -enumerateSubstringsInRange:options:usingBlock:
, if you call it on a mutable string, you can safely mutate the string being enumerated within the enclosingRange
. So, if you want to replace the matching words, you can with something like [aString replaceCharactersInRange:substringRange withString:replacementString]
.