string - 在 Swift 中快速转义 unicode 字符

标签 string swift unicode swift2

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

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

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

字符串数组是使用以下方法生成的:

myHTMLString = try NSString(contentsOfURL: url, encoding: NSUTF8StringEncoding)

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

并在遇到 "时将字符串拆分为不同的子字符串。

是否有更简单(并且可能更快)和更通用的方法来对 unicode 字符进行转义?

最佳答案

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

let transform = "Any-Hex/Java"
let input = "\\u5404\\u500b\\u90fd" as NSString
var convertedString = input.mutableCopy() as NSMutableString

CFStringTransform(convertedString, nil, transform as NSString, 1)

println("convertedString: \(convertedString)")
// convertedString: 各個都

见自:Using Swift to unescape unicode characters, ie \u1234

关于string - 在 Swift 中快速转义 unicode 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31220194/

相关文章:

arrays - 将数组存储到我在 bundle 中创建的 answer.json 文件

javascript - 如何在 JavaScript 中比较粗略的时间字符串

PHP - 从字符串中删除解码的 HTML 实体

java - 如何在属于 JLIst 的 DefaultListModel 的字符串中添加\t间距?

python - 如何在 Python 中替换字符串中的无效 unicode 字符?

c++ - 在 Windows 控制台应用程序中输出 unicode 字符串

python - 如何将 unicode 更改为 ascii 并删除无法识别的字符

Java每n行追加换行符

swift - 使用随机值 Swift 从 JSON 加载特定数据

Swift 嵌套函数与闭包变量