Number of Occurrences of a Character in NSString

Elliot picture Elliot · Jun 2, 2009 · Viewed 35.2k times · Source

I have an NSString or NSMutableString and would like to get the number of occurrences of a particular character.

I need to do this for quite a few characters -- uppercase English characters in this case -- so it would be nice for it to be quick.

Answer

gbaor picture gbaor · Mar 10, 2011

You can do this in one line. For example, this counts the number of spaces:

NSUInteger numberOfOccurrences = [[yourString componentsSeparatedByString:@" "] count] - 1;