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?
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);
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.