Number of occurrences of a substring in an NSString?
How can I get the number of times an NSString (for example, @"cake"
) appears in a larger NSString (for example, @"Cheesecake, apple cake, and cherry pie"
)?
I need to do this on a lot of strings, so whatever method I use would need to be relatively fast.
Thanks!
这没有经过测试,但应该是一个好的开始。
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:
上一篇: 在NSString中填充一个数字
下一篇: NSString中子字符串的出现次数?