在 Swift 中快速转义 unicode 字符

Afs*_*kla 1 string unicode swift swift2

如何快速转义 Swift Strings 中的 unicode 字符?现在,我有一个字符串数组,为了使其更易于用户阅读,我添加了以下代码来循环数组中的每个字符串

\n\n
for i in 0...(titles.count - 1) {\n    var s = titles[i]\n    s = s.stringByReplacingOccurrencesOfString(""", withString: "\\"")\n    s = s.stringByReplacingOccurrencesOfString("&", withString: "&")\n    s = s.stringByReplacingOccurrencesOfString("\\\\u00e1", withString: "\\u{00e1}")\n    s = s.stringByReplacingOccurrencesOfString("\\\\u00e9", withString: "\\u{00e9}")\n    s = s.stringByReplacingOccurrencesOfString("\\\\u00e8", withString: "\\u{00e8}")\n    s = s.stringByReplacingOccurrencesOfString("\\\\u00e0", withString: "\\u{00e0}")\n    s = s.stringByReplacingOccurrencesOfString("\\\\u00d8", withString: "\\u{00d8}")\n    s = s.stringByReplacingOccurrencesOfString("\\\\u00c3", withString: "\\u{00c3}")\n    s = s.stringByReplacingOccurrencesOfString("\\\\u00a4", withString: "\\u{00a4}")\n    s = s.stringByReplacingOccurrencesOfString("\\\\u00eb", withString: "\\u{00eb}")\n    s = s.stringByReplacingOccurrencesOfString("\\\\u2022", withString: "\\u{2022}")\n    s = s.stringByReplacingOccurrencesOfString("\\\\u00c9", withString: "\\u{00c9}")\n    s = s.stringByReplacingOccurrencesOfString("\\\\u00b3", withString: "\\u{00b3}")\n    s = s.stringByReplacingOccurrencesOfString("\\\\u2019", withString: "\\u{2019}")\n    s = s.stringByReplacingOccurrencesOfString("\\\\u2730", withString: "\\u{2730}")\n    s = s.stringByReplacingOccurrencesOfString("\\\\u266b", withString: "\\u{266b}")\n    s = s.stringByReplacingOccurrencesOfString("\\\\u00f8", withString: "\\u{00f8}")\n    s = s.stringByReplacingOccurrencesOfString("\\\\/", withString: "/")\n    titles[i] = s\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

例如,在第五行,任何出现的 都\\u00e1将替换为相应的 unicode 字符\xc3\xa1

\n\n

字符串数组是使用以下命令生成的:

\n\n
myHTMLString = try NSString(contentsOfURL: url, encoding: NSUTF8StringEncoding)\n
Run Code Online (Sandbox Code Playgroud)\n\n

在哪里url = NSURL(string: "http://songa.nl/ajax.php?params=playlist/load/US87OmpN")!

\n\n

当遇到“时,将字符串拆分为不同的子字符串。

\n\n

是否有一种更少的 hack-y(并且可能更快)、更通用的方法来转义 unicode 字符?

\n

Afs*_*kla 6

根据 Kerrek 的评论,并搜索“unes​​cape”而不是“resolve”,以下几行解决了我的问题:

\n\n
let transform = "Any-Hex/Java"\nlet input = "\\\\u5404\\\\u500b\\\\u90fd" as NSString\nvar convertedString = input.mutableCopy() as NSMutableString\n\nCFStringTransform(convertedString, nil, transform as NSString, 1)\n\nprintln("convertedString: \\(convertedString)")\n// convertedString: \xe5\x90\x84\xe5\x80\x8b\xe9\x83\xbd\n
Run Code Online (Sandbox Code Playgroud)\n\n

从:Using Swift to unescape unicode strings, ie \\u1234

\n