Matthew Flashen's answer was a good start for me. Here is what I ended up using in the form of a method. I made a slightly different approach to the cycle. This has been tested with empty strings passed to stringToCount and text, and with stringToCount, which occur as the first and / or last characters in the text.
I use this method regularly to count paragraphs in the submitted text (for example, stringToCount = @ "\ r").
I hope that someone will like it.
- (int)countString:(NSString *)stringToCount inText:(NSString *)text{ int foundCount=0; NSRange range = NSMakeRange(0, text.length); range = [text rangeOfString:stringToCount options:NSCaseInsensitiveSearch range:range locale:nil]; while (range.location != NSNotFound) { foundCount++; range = NSMakeRange(range.location+range.length, text.length-(range.location+range.length)); range = [text rangeOfString:stringToCount options:NSCaseInsensitiveSearch range:range locale:nil]; } return foundCount; }
An example call, assuming the method is in a class named myHelperClass ...
int foundCount = [myHelperClass countString:@"n" inText:@"Now is the time for all good men to come to the aid of their country"];
user278859 Jan 07 2018-11-11T00: 00Z
source share