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

丶灬走出姿态 提交于 2019-11-30 21:35:36

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!