我使用以下代码计算单词总数
-(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;
}
但是当我输入两行以上时,我得不到完美的计数。它需要换行...
请帮助.. !!!
答案 0 :(得分:9)
如果你真的想要计算单词(即“foo,bar”应该算作2个单词
然后是6个字符
您可以使用NSStringEnumerationByWords
的{{1}}选项,
它会自动处理所有空格和字分隔符:
enumerateSubstringsInRange
答案 1 :(得分:4)
你可以这样做:
NSString *text = @"Lorem ...";
NSArray *words = [text componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSInteger wordCount = [words count];
NSInteger characterCount = 0;
for (NSString *word in words) {
characterCount += [word length];
}
答案 2 :(得分:1)
一旦尝试这样,
NSString *string = @"123 1 2\n234\nponies";
NSArray *chunks = [string componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" \n"]];
NSLog(@"%d",[chunks count]);
答案 3 :(得分:0)
字数统计......
NSString *str = @"this is a sample string....";
NSScanner *scanner = [NSScanner scannerWithString:str];
NSCharacterSet *whiteSpace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSCharacterSet *nonWhitespace = [whiteSpace invertedSet];
int wordcount = 0;
while(![scanner isAtEnd])
{
[scanner scanUpToCharactersFromSet:nonWhitespace intoString:nil];
[scanner scanUpToCharactersFromSet:whitespace intoString:nil];
wordcount++;
}
答案 4 :(得分:0)
int characterCount = 0;
使用字数 -
NSArray *array = [txtView.text componentsSeparatedByString:@" "];
int wordCount = [array count];
for(int i = 0; i < [array count]; i++){
characterCount = characterCount + [[array objectAtIndex:i] length];
}
NSLog(@"characterCount : %i",characterCount);
NSLog(@"wordCount : %i",wordCount);
答案 5 :(得分:0)
str = textView.text;
NSArray *wordArray = [str componentsSeparatedByString:@" "];
int wordCount = [wordArray count];
int charCount=0;
for (int i=0 ; i < [wordArray count]; i++)
{
charCount = charCount + [[wordArray objectAtIndex:0] length];
}