Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i calculate the total number of words and character in textView? [duplicate]

i am using the following code to calculate the total number of words

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

and here is the code for the total character

 -(NSInteger) getTotalChars{

        NSString *str  =[_editor textInRange:[_editor textRangeWithRange:[self visibleRangeOfTextView:_editor]]];

        NSLog(@"%@",str);

        NSInteger charCount= [[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]length];

        return charCount=charCount-1;

    }

But i m not getting the perfect count when i enter more than two lines. it takes new line as word..

please help..!!!

like image 548
Sunny Shah Avatar asked Jun 27 '13 12:06

Sunny Shah


1 Answers

If you really want to count words (i.e. "foo,bar" should count as 2 words with 6 characters) then you can use the NSStringEnumerationByWords option of enumerateSubstringsInRange, which handles all the white space and word separators automatically:

NSString *string = @"Hello world.\nfoo,bar.";

__block int wordCount = 0;
__block int charCount = 0;
[string enumerateSubstringsInRange:NSMakeRange(0, [string length])
               options:NSStringEnumerationByWords
            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                wordCount += 1;
                charCount += substringRange.length;
            }];
NSLog(@"%d", wordCount); // Output: 4
NSLog(@"%d", charCount); // Output: 16
like image 135
Martin R Avatar answered Sep 28 '22 00:09

Martin R