Is this an acceptable way to find the number of occurrences of a substring? Could it be made any more efficient? And what encoding should be used to go from an NSString
to a c string?
I'm not 100% sure about the ()!=NULL
in the while statement, it seems to work fine and when there aren't any more occurrences found, it does break the while loop.
- (NSUInteger)occurenceOfString:(NSString *)substring {
const char *substr = [substring cStringUsingEncoding:NSUTF8StringEncoding];
const char *selfstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
unsigned long substrlen = strlen(substr);
NSUInteger count = 0;
char * ptr;
while ((ptr = strstr(selfstr, substr)) != NULL && substr != '\0') {
count++;
substr += substrlen + *ptr;
}
return count;
}
(It is a category method, so the string being searched in self).
NSUInteger cnt = 0, length = [str length];
NSRange range = NSMakeRange(0, length);
while(range.location != NSNotFound)
{
range = [str rangeOfString: @"substr" options:0 range:range];
if(range.location != NSNotFound)
{
range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
cnt++;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With