Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of occurrences of a substring in an NSString?

How can I get the number of times an NSString (for example, @"cake") 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.

Thanks!

like image 344
igul222 Avatar asked Jan 30 '10 04:01

igul222


People also ask

How do you count the number of substrings in a string?

count() Return Value count() method returns the number of occurrences of the substring in the given string.

How do I count the number of times a substring appears in a string in Java?

The goal is to calculate amount of occurrences of subStr in str. To do this, we use the formula: (a-b)/c, where a - length of str, b - length of str without all occurrences of subStr (we remove all occurrences of subStr from str for this), c - length of subStr.


1 Answers

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));     count++;    } } 
like image 83
Matthew Flaschen Avatar answered Oct 02 '22 13:10

Matthew Flaschen