ios – 如何计算textView中的单词和字符总数?

ios – 如何计算textView中的单词和字符总数?,第1张

概述参见英文答案 > Objective-C: -[NSString wordCount]                                    7个 我使用以下代码来计算单词总数 -(NSInteger) getTotalWords{ NSLog(@"Total Word %lu",[[_editor.attributedText string]length]); i 参见英文答案 > Objective-C: -[NSString wordCount]                                    7个
我使用以下代码来计算单词总数

-(NSInteger) getTotalWords{    NSLog(@"Total Word %lu",[[_editor.attributedText string]length]);    if ([[_editor.attributedText string]length]==0) {        return 0;    }    Nsstring *str  =[_editor textInRange:[_editor textRangeWithRange:[self visibleRangeOfTextVIEw:_editor]]];    NSInteger sepWord = [[[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]componentsSeparatedByString:@" "] count];    sepWord += [[[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]componentsSeparatedByString:@"\n"] count];    sepWord=sepWord-2;    return sepWord;}

这是整个角色的代码

-(NSInteger) getTotalChars{        Nsstring *str  =[_editor textInRange:[_editor textRangeWithRange:[self visibleRangeOfTextVIEw:_editor]]];        NSLog(@"%@",str);        NSInteger charCount= [[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]length];        return charCount=charCount-1;    }

但是,当我输入两行以上时,我得不到完美的计数.它需要换行的新词……

请帮忙..!!!

解决方法 你可以这样做:

Nsstring *text = @"Lorem ...";NSArray *words = [text componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];NSInteger wordCount = [words count];NSInteger characterCount = 0;for (Nsstring *word in words) {   characterCount += [word length];}
总结

以上是内存溢出为你收集整理的ios – 如何计算textView中的单词和字符总数?全部内容,希望文章能够帮你解决ios – 如何计算textView中的单词和字符总数?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/web/1053533.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存