NSString length with flag emojis

旧巷老猫 提交于 2019-12-11 13:59:50

问题


I'm trying to get the length of an NSString that contains a bunch of emojis, including the flag characters. Now I know how to get the length of a string containing emojis:

__block NSInteger length = 0;
[string enumerateSubstringsInRange:range
                           options:NSStringEnumerationByComposedCharacterSequences
                        usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
    length++;
}];

However, "NSStringEnumerationByComposedCharacterSequences" doesn't work in this case. Normal emojis are composed of two characters put together. The flag emojis are composed of two emoji-like characters put together. Thus the length of one flag emoji without any enumeration technique is 4.

How do I get the proper length (number of characters) of an NSString containing flag emojis?


回答1:


I tried the below solution. For normal emoji it returns 2 and for flags it will give 4. Also this will work with normal chars and special chars.

const char *cString = [string UTF8String];

int textLength = (int)strlen(cString);



回答2:


I strongly recommended you read This Article by Ole Begemann, which explains NSString/Unicode/Encoding, alone with talking about some pitfalls about NSString length count, comparison, etc.

According to this article:

You may use:

[text lengthOfBytesUsingEncoding:NSUTF32StringEncoding] / 4


来源:https://stackoverflow.com/questions/32365686/nsstring-length-with-flag-emojis

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