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!
count() Return Value count() method returns the number of occurrences of the substring in the given string.
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.
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++; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With