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
In this situation, I'd use an NSScanner like so:
NSString *str = @"this is a string";
NSScanner *scanner = [NSScanner scannerWithString:str];
NSCharacterSet *whiteSpace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSCharacterSet *nonWhitespace = [whiteSpace invertedSet];
int wordcount = 0;
while(![scanner isAtEnd])
{
[scanner scanUpToCharactersFromSet:nonWhitespace intoString:nil];
[scanner scanUpToCharactersFromSet:whitespace intoString:nil];
wordcount++;
}
This only creates two additional objects, no matter how long the string is.