简体   繁体   English

将字符串中的 unicode 符号 \\uXXXX 转换为 Swift 中的字符

[英]Convert unicode symbols \uXXXX in String to Character in Swift

I'm receiving via a REST API a string which contains unicode encoded characters in form of \\uXXXX我通过 REST API 接收一个字符串,其中包含\\uXXXX形式的 unicode 编码字符

eg Ain\’t which should be Ain't例如Ain\’t应该是Ain't

Is there a nice way to convert these?有没有好的方法来转换这些?

You can use \\u{my_unicode} :您可以使用\\u{my_unicode}

print("Ain\u{2019}t this a beautiful day")
/* Prints "Ain’t this a beautiful day"

From the Language Guide - Strings and Characters - Unicode :语言指南 - 字符串和字符 - Unicode

String literals can include the following special characters:字符串文字可以包含以下特殊字符:

... ...

  • An arbitrary Unicode scalar, written as \\u{n}, where n is a 1–8 digit hexadecimal number with a value equal to a valid Unicode code point任意 Unicode 标量,写为 \\u{n},其中 n 是 1-8 位十六进制数,其值等于有效的 Unicode 代码点

You can apply a string transform StringTransform :您可以应用字符串转换StringTransform

extension String {
    var decodingUnicodeCharacters: String { applyingTransform(.init("Hex-Any"), reverse: false) ?? "" }
}

let string = #"Ain\u2019t"#
print(string.decodingUnicodeCharacters)  // "Ain’t\n"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM