Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of Occurrences of a Character in NSString

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.

like image 216
Elliot Avatar asked Jun 02 '09 06:06

Elliot


3 Answers

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

NSUInteger numberOfOccurrences = [[yourString componentsSeparatedByString:@" "] count] - 1;
like image 100
gbaor Avatar answered Sep 19 '22 21:09

gbaor


Try this category on NSString:

@implementation NSString (OccurrenceCount)

- (NSUInteger)occurrenceCountOfCharacter:(UniChar)character
{
    CFStringRef selfAsCFStr = (__bridge CFStringRef)self;

    CFStringInlineBuffer inlineBuffer;
    CFIndex length = CFStringGetLength(selfAsCFStr);
    CFStringInitInlineBuffer(selfAsCFStr, &inlineBuffer, CFRangeMake(0, length));

    NSUInteger counter = 0;

    for (CFIndex i = 0; i < length; i++) {
        UniChar c = CFStringGetCharacterFromInlineBuffer(&inlineBuffer, i);
        if (c == character) counter += 1;
    }

    return counter;
}

@end

This one is approximately 5 times faster than the componentsSeparatedByString: approach.

like image 26
Jacque Avatar answered Sep 20 '22 21:09

Jacque


replaceOccurrencesOfString:withString:options:range: will return the number of characters replaced in a NSMutableString.

[string replaceOccurrencesOfString:@"A" 
                        withString:@"B" 
                           options:NSLiteralSearch 
                             range:NSMakeRange(0, [receiver length])];
like image 16
CynicismRising Avatar answered Sep 22 '22 21:09

CynicismRising