How to count words within a text string?

前端 未结 4 992
面向向阳花
面向向阳花 2021-01-01 07:47

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

相关标签:
4条回答
  • 2021-01-01 07:59

    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

    0 讨论(0)
  • 2021-01-01 08:01
     [[stringToCOunt componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceCharacterSet] count]
    
    0 讨论(0)
  • 2021-01-01 08:16

    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.

    0 讨论(0)
  • 2021-01-01 08:16

    One liner accurate solution:

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

    This solution handles consecutive spaces correctly.

    0 讨论(0)
提交回复
热议问题