How do you get the number of words in a NSTextStorage/NSString?
So my question is basically how do you get the number of words in a NSTextStorage/N开发者_StackOverflow社区SString? I don't want the character length but the word length. Thanks.
If you're on 10.6 or later, the following may be the easiest solution:
- (NSUInteger)numberOfWordsInString:(NSString *)str {
__block NSUInteger count = 0;
[str enumerateSubstringsInRange:NSMakeRange(0, [str length])
options:NSStringEnumerationByWords|NSStringEnumerationSubstringNotRequired
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
count++;
}];
return count;
}
If you want to take the current locale into account when doing word-splitting you can also add NSStringEnumerationLocalized to the options.
You could always find the number of spaces and add one. To be more accurate one would have to take into all nonletter characters: commas, fullstops, whitespace characters, etc.
[[string componentsSeparatedByString:@" "] count];
When using NSTextStorage
, you can use the words
method to get to the number of words. It might not be the most memory-efficient way to count words, but it does a pretty good job at ignoring punctuation marks and other non-word characters:
NSString *input = @"one - two three four .";
NSTextStorage *storage = [[NSTextStorage alloc] initWithString:input];
NSLog(@"word count: %u", [[storage words] count]);
The output will be word count: 4
.
CFStringTokenizer
is your friend.
Use that:
NSArray *words = [theStorage words];
int wordCount = [words count];
Is that your problem?
精彩评论