wakaka
wakaka

Reputation: 553

Finding how many instances of a specific text in a TextView for Objective C

I am starting to learn how to code a mac application using Objective C. Right now I have a TextView filled up with text. Is there any way I can get the number of instances a specific word appearing in that textview.

I have read up on NSTextFinder Class but I can't set my TextView as the client of the NSTextFinder and there is no sample code to help me along. Any help is appreciated

Upvotes: 0

Views: 183

Answers (1)

FluffulousChimp
FluffulousChimp

Reputation: 9185

I'm assuming that all you need to do is provide a standard Cocoa find bar capability for NSTextView in which case it's just self.textView.usesFindBar = YES for the NSTextView in question. When the users presses COMMAND + F

Perhaps you're looking for a solution that doesn't use the find UI - but then you wouldn't be using NSTextFinder whose function is to serve as the find UI's controller class... If you're looking for a non-UI-based search and count mechanism then edit your question and we can try to respond.

EDIT:

If you just want to count the occurrences of a word in the NSTextView's then NSScanner is a solution. See example of NSScanner as word counter in action:

#import <Foundation/Foundation.h>

int main(int argc, char *argv[]) {
    NSAutoreleasePool *p = [[NSAutoreleasePool alloc] init];

    NSString *sampleString = @"The dog ate my homework. Later, \
         the dog ate my lunch.  Sometimes, dogs do that.";
    NSScanner *scanner = [NSScanner scannerWithString:sampleString];
    NSString *aDog = nil;
    NSInteger wordCount = 0;
    while( ![scanner isAtEnd] ) {
        if( [scanner scanUpToString:@"dog" intoString:&aDog] ) {
            if( [scanner scanString:@"dog" intoString:&aDog] ) {
                wordCount++;
            }
        }
    }
    printf("There are %ld dog words in the text.\n",wordCount);
    [p release];
}

This prints out:

There are 3 dog words in the text.

Upvotes: 3

Related Questions