在Swift中将Unicode标量表情符号转换为String [英] Convert unicode scalar emoji to String in Swift
问题描述
我从服务器获取的文本字符串中的表情符号获得了unicode标量,当我在 UILabel
中打印它们时,它们无法显示为表情符号。这是从服务器获取字符串的格式:
I'm getting unicode scalar for emojis in a text string that I get from a server, which fail to show up as emojis when I print them in a UILabel
. This is the format in which I get my string from server:
let string = "Hi, I'm lily U+1F609"
除非更改为
let string = "Hi, I'm lily \u{1F609}"
反正我可以将字符串转换为所需的格式吗?
Is there anyway I can convert the string to the required format?
我不想使用正则表达式来确定出现的情况 U +< HEX_CODE>
,然后将它们转换为 \u {HEX_CODE}
。必须有一个更好的方法来做到这一点。
I don't want to use a regex to determine occurrences of U+<HEX_CODE>
and then converting them to \u{HEX_CODE}
. There has to be a better way of doing this.
推荐答案
这是正则表达式的创建对象。如果有更简单的非正则表达式解决方案,我将删除以下答案:
This is the very kind of problems that regex was created for. If there's a simpler non-regex solution, I'll delete this answer:
func replaceWithEmoji(str: String) -> String {
var result = str
let regex = try! NSRegularExpression(pattern: "(U\\+([0-9A-F]+))", options: [.CaseInsensitive])
let matches = regex.matchesInString(result, options: [], range: NSMakeRange(0, result.characters.count))
for m in matches.reverse() {
let range1 = m.rangeAtIndex(1)
let range2 = m.rangeAtIndex(2)
if let codePoint = Int(result[range2], radix: 16) {
let emoji = String(UnicodeScalar(codePoint))
let startIndex = result.startIndex.advancedBy(range1.location)
let endIndex = startIndex.advancedBy(range1.length)
result.replaceRange(startIndex..<endIndex, with: emoji)
}
}
return result
}
这篇关于在Swift中将Unicode标量表情符号转换为String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!