How to replace emoji characters with their descriptions in a Swift string

喜夏-厌秋 提交于 2019-12-05 15:30:40

Simply do not use a Character in the first place but use a String as input:

let cfstr = NSMutableString(string: "This 😄 is my string 😄") as CFMutableString

that will finally output

This {SMILING FACE WITH OPEN MOUTH AND SMILING EYES} is my string {SMILING FACE WITH OPEN MOUTH AND SMILING EYES}

Put together:

func transformUnicode(input : String) -> String {
    let cfstr = NSMutableString(string: input) as CFMutableString
    var range = CFRangeMake(0, CFStringGetLength(cfstr))
    CFStringTransform(cfstr, &range, kCFStringTransformToUnicodeName, Bool(0))
    let newStr = "\(cfstr)"
    return newStr.stringByReplacingOccurrencesOfString("\\N", withString:"")
}

transformUnicode("This 😄 is my string 😄")
Cue

Here is a complete implementation.

It avoids to convert to description also the non-emoji characters (e.g. it avoids to convert to {LEFT DOUBLE QUOTATION MARK}). To accomplish this, it uses an extension based on this answer by Arnold that returns true or false whether a string contains an emoji.

The other part of the code is based on this answer by MartinR and the answer and comments to this answer by luk2302.

var str = "Hello World 😄 …" // our string (with an emoji and a horizontal ellipsis)

let newStr = str.characters.reduce("") { // loop through str individual characters
    var item = "\($1)" // string with the current char
    let isEmoji = item.containsEmoji // true or false
    if isEmoji {
        item = item.stringByApplyingTransform(String(kCFStringTransformToUnicodeName), reverse: false)!
    }
    return $0 + item
}.stringByReplacingOccurrencesOfString("\\N", withString:"") // strips "\N"


extension String {
    var containsEmoji: Bool {
        for scalar in unicodeScalars {
            switch scalar.value {
            case 0x1F600...0x1F64F, // Emoticons
            0x1F300...0x1F5FF, // Misc Symbols and Pictographs
            0x1F680...0x1F6FF, // Transport and Map
            0x2600...0x26FF,   // Misc symbols
            0x2700...0x27BF,   // Dingbats
            0xFE00...0xFE0F,   // Variation Selectors
            0x1F900...0x1F9FF:   // Various (e.g. 🤖)
                return true
            default:
                continue
            }
        }
        return false
    }
}

print (newStr) // Hello World {SMILING FACE WITH OPEN MOUTH AND SMILING EYES} …

Please note that some emoji could not be included in the ranges of this code, so you should check if all the emoji are converted at the time you will implement the code.

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