Objective-C: -[NSString wordCount]

ma11hew28 picture ma11hew28 · May 30, 2011 · Viewed 8.4k times · Source

What's a simple implementation of the following NSString category method that returns the number of words in self, where words are separated by any number of consecutive spaces or newline characters? Also, the string will be less than 140 characters, so in this case, I prefer simplicity & readability at the sacrifice of a bit of performance.

@interface NSString (Additions)
- (NSUInteger)wordCount;
@end

I found the following solutions:

But, isn't there a simpler way?

Answer

Sedate Alien picture Sedate Alien · May 30, 2011

Why not just do the following?

- (NSUInteger)wordCount {
    NSCharacterSet *separators = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSArray *words = [self componentsSeparatedByCharactersInSet:separators];

    NSIndexSet *separatorIndexes = [words indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        return [obj isEqualToString:@""];
    }];

    return [words count] - [separatorIndexes count];
}