快速浏览Swift

时间:2015-07-04 11:40:46

标签: string swift unicode swift2

你如何快速浏览Swift Strings中的unicode字符?现在,我有一个字符串数组,为了使其更具用户可读性,我添加了以下代码循环遍历数组中的每个String

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")!

并将字符串拆分为不同的子串,当"遇到了。

unescape unicode字符是否有更少的hack-y(可能更快)和更通用的方式?

1 个答案:

答案 0 :(得分:2)

根据Kerrek的评论,并搜索'unescape'而不是'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