加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 19:33:22 所属栏目:百科 来源:网络整理
导读:参见英文答案 Objective-C: -[NSString wordCount]????????????????????????????????????7个 我使用以下代码来计算单词总数 -(NSInteger) getTotalWords{ NSLog(@"Total Word %lu",[[_editor.attributedText string]length]); if ([[_editor.attributedText
参见英文答案 > 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];
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读