所以我的问题基本上是如何获得NSTextStorage / NSString中的单词数量?我不想要字符长度而是字长。感谢。
答案 0 :(得分:8)
如果您使用的是10.6或更高版本,以下内容可能是最简单的解决方案:
- (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;
}
如果要在进行分词时考虑当前区域设置,还可以将NSStringEnumerationLocalized添加到选项中。
答案 1 :(得分:1)
您始终可以找到空格数并添加一个空格。 为了更准确,我们必须考虑所有非字母字符:逗号,fullstops,空格字符等。
[[string componentsSeparatedByString:@" "] count];
答案 2 :(得分:1)
使用NSTextStorage
时,您可以使用words
方法获取字数。它可能不是计算单词的最有效记忆方式,但它在忽略标点符号和其他非单词字符方面表现相当不错:
NSString *input = @"one - two three four .";
NSTextStorage *storage = [[NSTextStorage alloc] initWithString:input];
NSLog(@"word count: %u", [[storage words] count]);
输出为word count: 4
。
答案 3 :(得分:0)
CFStringTokenizer
是你的朋友。
答案 4 :(得分:0)
使用:
NSArray *words = [theStorage words];
int wordCount = [words count];
这是你的问题吗?