How to count words in a text string?

In iOS, how can I count words within a specific text string?

+1
source share
4 answers

A more efficient way than splitting is to check the string character with 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 to @ennuikiller's solution , counting a line of 1,000,000 words, you need:

  • 0.19 seconds to create a string
  • 0.39 seconds to build a row + count using my method.
  • 1.34 seconds to build a row + count using the ennuikiller method.

A big drawback of my method is that it is not single line.

+7
source
 [[stringToCOunt componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceCharacterSet] count]
+4
source

, :

__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 out the video recording of WWDC 2012 session 215: text and linguistic analysis by Douglas Davidson

+2
source

One linear exact solution:

return [[self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length > 0"]].count;
0
source

All Articles