5

次のコードを使用して単語の総数を計算しています

-(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;

    }

しかし、2行以上入力すると完璧なカウントが得られません。それは単語として新しい行を取ります..

助けてください..!!!

4

6 に答える 6

1

一度このようにしてみてください、

 NSString *string = @"123 1 2\n234\nponies";
    NSArray *chunks = [string componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" \n"]];
    NSLog(@"%d",[chunks count]);
于 2013-06-27T12:44:28.760 に答える
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++;
}
于 2013-06-27T12:27:51.410 に答える
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);
于 2013-06-27T12:40:37.637 に答える
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];
    }
于 2013-06-27T12:41:12.870 に答える