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.
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.
I would probably use
NSString rangeOfCharacterFromSet:
or
rangeOfCharacterFromSet:options:range::
where the set is the set of characters you're searching for. It returns with the location of first character matching the set. Keep array or dictionary and increment the count for character, then repeat.
replaceOccurrencesOfString:withString:options:range:
will return the number of characters replaced in aNSMutableString
.The example with the Scanner was crashing on iPhone. I found this solution :
It worked for me without crash. Hope it can help !
Whenever you are looking for things in a
NSString
, try usingNSScanner
first.Nowadays the first thing that come to my mind for something like that: NSCountedSet
logs:
You can do this in one line. For example, this counts the number of spaces: