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).