如何用 Swift 字符串中的描述替换表情符号字符

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

我正在寻找一种方法来用 Swift 字符串中的描述替换表情符号字符。

示例:

Input "This is my string "

我想替换为:

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

到目前为止,我使用的是从 this answer by MartinR 的原始代码修改而来的代码,但它仅在我处理单个字符时有效。

let myCharacter : Character = ""
let cfstr = NSMutableString(string: String(myCharacter)) as CFMutableString
var range = CFRangeMake(0, CFStringGetLength(cfstr))
CFStringTransform(cfstr, &range, kCFStringTransformToUnicodeName, Bool(0))
var newStr = "\(cfstr)"

// removing "\N"  from the result: \N{SMILING FACE WITH OPEN MOUTH AND SMILING EYES}
newStr = newStr.stringByReplacingOccurrencesOfString("\N", withString:"")

print("\(newStr)") // {SMILING FACE WITH OPEN MOUTH AND SMILING EYES}

我怎样才能做到这一点?

首先不要使用 Character,而是使用 String 作为输入:

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

最终会输出

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

合计:

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 ")

这是一个完整的实现。

它避免将非表情符号字符也转换为描述(例如,它避免将 转换为 {左双引号}).为此,它使用基于 的扩展,即 returns true 或 false 字符串是否包含表情符号。

其他部分代码基于this answer by MartinR and the answer and comments to .

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 = "\()" // string with the current char
    let isEmoji = item.containsEmoji // true or false
    if isEmoji {
        item = item.stringByApplyingTransform(String(kCFStringTransformToUnicodeName), reverse: false)!
    }
    return [=10=] + 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} …

请注意,部分表情符号无法包含在此代码的范围内,因此您在执行代码时应检查是否所有表情符号都已转换。