问题
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