Alex Stone
Alex Stone

Reputation: 47344

iPhone iOS how to count number of case-insensitive occurrences of a word within a string?

I'm looking for a way to search an arbitrary long string (10000 characters) and find the number of times a specific keyword is repeated in the string. How can this be done?

I have this method, that pretty much counts the number of fragments left after the string is split around keywords, but it is not case insensitive.

-(void)countKeywords
{
    NSArray* components = [self.salesCopy componentsSeparatedByString:@"search term"];

    NSLog(@"search term number found: %i",components.count);


}

What's a better way to count the number of keywords within a string?

Upvotes: 3

Views: 1300

Answers (3)

TommyG
TommyG

Reputation: 4155

I am not 100% sure that could help you, but may do some of the job you need (if not all):

NSRange ran = [yourString rangeOfString:wordToLookFor options:NSCaseInsensitiveSearch];

And look at

ran.length
ran.location

ran.location will provide you the location within the string of the first occurrence. You could then cut the string after this occurrence, and run this again until the end of the string.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

Splitting the string, counting parts, and throwing them away is not efficient. Searching for substring repeatedly without creating new objects would definitely be more efficient. Since the string is relatively long, you may benefit from implementing an advanced string search algorithm, for example Knuth-Morris-Pratt, to significantly decrease your search time.

Here is an implementation that should be faster than your splitting code:

NSString *str = @"Hello sun, hello bird, hello my lady! Hello breakfast, May I buy you again tomorrow?";
NSRange r = NSMakeRange(0, str.length);
int count = 0;
for (;;) {
    r = [str rangeOfString:@"hello" options:NSCaseInsensitiveSearch range:r];
    if (r.location == NSNotFound) {
        break;
    }
    count++;
    r.location++;
    r.length = str.length - r.location;
}
NSLog(@"%d", count);

Upvotes: 3

Andy Obusek
Andy Obusek

Reputation: 12842

Just create copies of both self.salesCopy and the searchTerm, set the copies to lower case via [NSString lowercaseString], then perform your code, and you'll have the count

-(void)countKeywords
{
    NSString *lowerCaseSalesCopy = [self.salesCopy lowercaseString];
    NSString *lowerCaseSearchTerm = [searchTerm lowercaseString];
    NSArray* components = [lowerCaseSalesCopy componentsSeparatedByString:lowerCaseSearchTerm];

    NSLog(@"search term number found: %i",components.count);
}

Upvotes: 2

Related Questions