开发者

How to count words within a text string?

On iOS, how can I cou开发者_运维技巧nt words within a specific text string?


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:

  • 0.19 seconds to build the string
  • 0.39 seconds to build the string + counting using my method.
  • 1.34 seconds to build the string + counting using ennuikiller's method.

The big disadvantage of my method is that it's not a one-liner.


 [[stringToCOunt componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceCharacterSet] count]


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


One liner accurate solution:

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

This solution handles consecutive spaces correctly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜