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

时间:2016-06-11 17:27:55

标签: xcode string swift emoji

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

示例:

  

输入"This is my string "

我想替换以获取:

  

输出"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}

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:7)

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

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

将最终输出

  

这个{露出嘴巴和微笑的笑脸}是我的字符串{SMING 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 ")

答案 1 :(得分:1)

这是一个完整的实施。

它避免将非表情符号转换为描述(例如,它避免将转换为 {LEFT DOUBLE QUOTATION MARK} )。为实现此目的,它使用基于this answer by Arnold的扩展,无论字符串是否包含表情符号,都会返回true或false。

代码的其他部分基于this answer by MartinR以及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} …

请注意,某些表情符号不能包含在此代码的范围内,因此您应该检查在实现代码时是否转换了所有表情符号。