IPhone iOS, how to count the number of case-insensitive occurrences of a word in a string?

I am looking for a way to search for an arbitrary long string (10,000 characters) and find the number of repetitions of a particular keyword in a string. How can I do that?

I have this method, which pretty much takes into account the number of fragments left after the string is split by keywords, but it is not case sensitive.

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

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


}

What is the best way to count the number of keywords per line?

+3
source share
3 answers

, . . , , Knuth-Morris-Pratt, .

, , :

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);
+3

self.salesCopy, searchTerm, [NSString lowercaseString], ,

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

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

100%, , , ( ):

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

ran.length
ran.location

ran.location . .

+1

All Articles