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?
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];
}
I believe you have identified the 'simplest'. Nevertheless, to answer to your original question - "a simple implementation of the following NSString category...", and have it posted directly here for posterity:
@implementation NSString (GSBString)
- (NSUInteger)wordCount
{
__block int words = 0;
[self enumerateSubstringsInRange:NSMakeRange(0,self.length)
options:NSStringEnumerationByWords
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {words++;}];
return words;
}
@end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With