With recently added iOS 9.1 emojis, and the availability of skin tones etc, how do you properly count the number of Emojis in a String, assuming the string is uniquely made out of emojis?
Keep in mind that the length of emojis can vary.
NSString.length or string.characters.count
"π" returns 2
"βπΏ" returns 4
"π§πΈ" or "π§πΈ" or "π§πΈπ§πΈπ§πΈπ§πΈπ§πΈπ§πΈ" returns 1!
"π¨βπ©βπ§βπ§" returns 4 (Should be normally displayed as 1 family emoji)
etc...
Emojis or Unicode. Standard emojis count as two characters when writing a message.
π How many emoji characters are there? π In total there are 3,633 emojis in the Unicode Standard, as of September 2021.
> Most of the emoji are 3-byte Unicode characters. The most recent Emoji standard has 1,182 characters classified as Emoji and 179 of them are in the BMP [1]. Others are encoded as 4 bytes in any UTF encodings.
It may seem like a small change, but due to how Unicode, the organization that ensures emoji encoding is consistent across platforms, rendered certain emoji characteristics like gender and race in an emoji could sometimes eat up multiple characters. And as we know, in a tweet, every character counts.
I make an extension of String
to count number of emoji in a string:
extension String {
func countEmojiCharacter() -> Int {
func isEmoji(s:NSString) -> Bool {
let high:Int = Int(s.characterAtIndex(0))
if 0xD800 <= high && high <= 0xDBFF {
let low:Int = Int(s.characterAtIndex(1))
let codepoint: Int = ((high - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000
return (0x1D000 <= codepoint && codepoint <= 0x1F9FF)
}
else {
return (0x2100 <= high && high <= 0x27BF)
}
}
let nsString = self as NSString
var length = 0
nsString.enumerateSubstringsInRange(NSMakeRange(0, nsString.length), options: NSStringEnumerationOptions.ByComposedCharacterSequences) { (subString, substringRange, enclosingRange, stop) -> Void in
if isEmoji(subString!) {
length++
}
}
return length
}
}
Test:
let y = "xxxππ¨π°π¨π°zzz"
print(y.countEmojiCharacter())
// result is 3
try this code snippet
extension String {
var composedCount : Int {
var count = 0
enumerateSubstringsInRange(startIndex..<endIndex, options: .ByComposedCharacterSequences) {_ in count++}
return count
}
}
: credit goes to ericasadun
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With