I am a bit new to Objective C and was wondering if there is a better way to count words in a string.
ie:
NSString *str = @\"this is a string\";
// r
This code will count the number of words (i.e., non-empty substrings) contained in a string that are separated by any number of space or line break characters:
NSUInteger wordCount = 0;
for (NSString* word in [someString
componentsSeparatedByCharactersInSet:
[NSMutableCharacterSet characterSetWithCharactersInString:@" \n"]]) {
if (![word isEqual: @""]) {
wordCount++;
}
}
It's a slight improvement to zoul's answer without recurring to regexes.