Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of characters in a string (not number of bytes)

In a string in objective-c if I say something like [myStr length]; it returns a number which is the number of bytes but what can I use to return the number of characters in a string.

For example:
a string with the letter "a" in it returns a length of 1
a string with a single emoji in it returns a length of 2 (or even a length of 4 sometimes)


this is because that is the number of bytes in the string... I just need the number of characters.

like image 880
Albert Renshaw Avatar asked Mar 10 '13 22:03

Albert Renshaw


1 Answers

I just whipped up this method. Add it to an NSString category.

- (NSUInteger)characterCount {
    NSUInteger cnt = 0;
    NSUInteger index = 0;
    while (index < self.length) {
        NSRange range = [self rangeOfComposedCharacterSequenceAtIndex:index];
        cnt++;
        index += range.length;
    }

    return cnt;
}

NSString *a = @"Hello";
NSLog(@"%@ length = %u, chars = %u", a, a.length, a.characterCount);
NSString *b = @"🏁 Emoji 📳";
NSLog(@"%@ length = %u, chars = %u", b, b.length, b.characterCount);

This yields:

Hello length = 5, chars = 5
🏁 Emoji 📳 length = 11, chars = 9

like image 151
rmaddy Avatar answered Oct 01 '22 03:10

rmaddy