我使用下面的代碼來計算的話如何計算textView中的單詞和字符總數?
-(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;
}
但是,當我輸入超過我不是得到完美的計數的代碼兩條線。它需要新的一行作爲字..
請幫助.. !!!
'的myString = [myString的stringByReplacingOccurrencesOfString:@ 「\ n」 withString :@「」];' –
這是一個完美的答案... – mindfreak
http://stackoverflow.com/questions/6171422/objective-c-nsstring-wordcount http://stackoverflow.com/questions/4724206/how-do-you-get-the-number-of-words-in- a-nstextstorage-nsstring http://stackoverflow.com/questions/3975209/what-is-the-most-efficient-way-to-count-number-of-word-in-nsstring-without-using 很多重複。 – doge