Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of occurrences of substring in string [duplicate]

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

like image 233
Jonathan. Avatar asked Feb 23 '23 16:02

Jonathan.


1 Answers

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++; 
  }
}
like image 177
Lelouch Lamperouge Avatar answered Feb 25 '23 15:02

Lelouch Lamperouge