4

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

chown
  • 51,908
  • 16
  • 134
  • 170
Jonathan.
  • 53,997
  • 54
  • 186
  • 290
  • This is similar to http://stackoverflow.com/questions/2166809/number-of-occurrences-of-a-substring-in-an-nsstring NSUTF8StringEncoding is the right encoding. – Jano Oct 16 '11 at 18:02

1 Answers1

8
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++; 
  }
}
Lelouch Lamperouge
  • 8,171
  • 8
  • 49
  • 60
  • +1. This is the only way to do it since it automatically takes care of the unicode foobar! – JustSid Oct 16 '11 at 17:54
  • @JustSid, what do you mean about unicode foobar? – Jonathan. Oct 19 '11 at 19:57
  • I mean that NSString takes care of Unicode handling, while your code doesn't even allow Unicode which might break once you throw your app on the international market. – JustSid Oct 19 '11 at 20:07