Count The Number of Words in an NSString

Here’s a quick way to count the number of words in an NSString object. The trick is to use the character set whitespaceAndNewlineCharacterSet which will look for spaces, tabs and newline characters.

- (NSUInteger)wordCount:(NSString *)str 
{
  NSUInteger words = 0;
 
  NSScanner *scanner = [NSScanner scannerWithString: str];
 
  // Look for spaces, tabs and newlines
  NSCharacterSet *whiteSpace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
  while ([scanner scanUpToCharactersFromSet:whiteSpace  intoString:nil])
    words++;
 
  return words;
}

If you have another way to reach the same result, please post a code sample.