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: