Objective-C: -[NSString wordCount]

后端 未结 7 1212
孤街浪徒
孤街浪徒 2020-12-05 21:39

What\'s a simple implementation of the following NSString category method that returns the number of words in self, where words are separated by an

7条回答
  •  北荒
    北荒 (楼主)
    2020-12-05 21:59

    There are a number of simpler implementations, but they all have tradeoffs. For example, Cocoa (but not Cocoa Touch) has word-counting baked in:

    - (NSUInteger)wordCount {
        return [[NSSpellChecker sharedSpellChecker] countWordsInString:self language:nil];
    }
    

    It's also trivial to count words as accurately as the scanner simply using [[self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] count]. But I've found the performance of that method degrades a lot for longer strings.

    So it depends on the tradeoffs you want to make. I've found the absolute fastest is just to go straight-up ICU. If you want simplest, using existing code is probably simpler than writing any code at all.

提交回复
热议问题