On iOS, how can I count words within a specific text string?
I think this method is better:
__block int wordCount = 0;
NSRange range = {0,self.text.length };
[self.text enumerateSubstringsInRange:range options:NSStringEnumerationByWords usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
wordCount++;
}];
As a reference check the video of the session 215 of the WWDC 2012: Text and Linguistic Analysis by Douglas Davidson
[[stringToCOunt componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceCharacterSet] count]
A more efficient method than splitting is to check the string character by character.
int word_count(NSString* s) {
CFCharacterSetRef alpha = CFCharacterSetGetPredefined(kCFCharacterSetAlphaNumeric);
CFStringInlineBuffer buf;
CFIndex len = CFStringGetLength((CFStringRef)s);
CFStringInitInlineBuffer((CFStringRef)s, &buf, CFRangeMake(0, len));
UniChar c;
CFIndex i = 0;
int word_count = 0;
Boolean was_alpha = false, is_alpha;
while (c = CFStringGetCharacterFromInlineBuffer(&buf, i++)) {
is_alpha = CFCharacterSetIsCharacterMember(alpha, c);
if (!is_alpha && was_alpha)
++ word_count;
was_alpha = is_alpha;
}
if (is_alpha)
++ word_count;
return word_count;
}
Compared with @ennuikiller's solution, counting a 1,000,000-word string takes:
The big disadvantage of my method is that it's not a one-liner.
One liner accurate solution:
return [[self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length > 0"]].count;
This solution handles consecutive spaces correctly.