Number of occurrences of a substring in an NSString? Number of occurrences of a substring in an NSString? objective-c objective-c

Number of occurrences of a substring in an NSString?


This isn't tested, but should be a good start.

NSUInteger count = 0, length = [str length];NSRange range = NSMakeRange(0, length); while(range.location != NSNotFound){  range = [str rangeOfString: @"cake" options:0 range:range];  if(range.location != NSNotFound)  {    range = NSMakeRange(range.location + range.length, length - (range.location + range.length));    count++;   }}


A regex like the one below should do the job without a loop interaction...

Edited

NSString *string = @"Lots of cakes, with a piece of cake.";NSError *error = NULL;NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"cake" options:NSRegularExpressionCaseInsensitive error:&error];NSUInteger numberOfMatches = [regex numberOfMatchesInString:string options:0 range:NSMakeRange(0, [string length])];NSLog(@"Found %i",numberOfMatches);

Only available on iOS 4.x and superiors.


was searching for a better method then mine but here's another example:

NSString *find = @"cake";NSString *text = @"Cheesecake, apple cake, and cherry pie";NSInteger strCount = [text length] - [[text stringByReplacingOccurrencesOfString:find withString:@""] length];strCount /= [find length];

I would like to know which one is more effective.

And I made an NSString category for better usage:

// NSString+CountString.m@interface NSString (CountString)- (NSInteger)countOccurencesOfString:(NSString*)searchString;@end@implementation NSString (CountString)- (NSInteger)countOccurencesOfString:(NSString*)searchString {    NSInteger strCount = [self length] - [[self stringByReplacingOccurrencesOfString:searchString withString:@""] length];    return strCount / [searchString length];}@end

simply call it by:

[text countOccurencesOfString:find];

Optional: you can modify it to search case insensitive by defining options: