igul222 igul222 - 1 year ago 71
Objective-C Question

Number of occurrences of a substring in an NSString?

How can I get the number of times an NSString (for example,

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


Answer Source

This isn't tested, but should be a good start.

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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download