如何获取NSTextStorage / NSString中的字数? [英] How do you get the number of words in a NSTextStorage/NSString?
本文介绍了如何获取NSTextStorage / NSString中的字数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我的问题是基本上你是如何得到NSTextStorage / NSString中的字数?我不想要的字符长度,但字长。谢谢。
So my question is basically how do you get the number of words in a NSTextStorage/NSString? I don't want the character length but the word length. Thanks.
推荐答案
如果您使用的是10.6或更高版本,以下是最简单的解决方案:
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;
}
如果要在分词时考虑当前语言环境也可以添加NSStringEnumerationLocalized到选项。
If you want to take the current locale into account when doing word-splitting you can also add NSStringEnumerationLocalized to the options.
这篇关于如何获取NSTextStorage / NSString中的字数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文