1
作为一个通用的解决方案,我们如何获得Swift中字符或字符串的unicode代码点/ s?如何在Swift中获得字符/字符串的unicode代码点表示?
考虑以下几点:
let A: Character = "A" // "\u{0041}"
let Á: Character = "Á" // "\u{0041}\u{0301}"
let sparklingHeart = "" // "\u{1F496}"
let SWIFT = "SWIFT" // "\u{0053}\u{0057}\u{0049}\u{0046}\u{0054}"
如果我没有弄错,所需的功能可能会返回一个字符串数组,例如:
extension Character {
func getUnicodeCodePoints() -> [String] {
//...
}
}
A.getUnicodeCodePoints()
// the output should be: ["\u{0041}"]
Á.getUnicodeCodePoints()
// the output should be: ["\u{0041}", "\u{0301}"]
sparklingHeart.getUnicodeCodePoints()
// the output should be: ["\u{1F496}"]
SWIFT.getUnicodeCodePoints()
// the output should be: ["\u{0053}", "\u{0057}", "\u{0049}", "\u{0046}", "\u{0054}"]
任何更多的建议简洁的方法,将不胜感激。
谢谢您的回答。请注意,我得到的print(Array(“Á”.unicodeScalars))的输出是'[“\ u {00C1}”]',但* not *'[“A”,“\ u {0301}” ]',类似于这种情况,我试过:'print(Array(“é”.unicodeScalars))'并且输出是'[“\ u”}“],但不是'[”u“,”e \ ∪{0301}“]';我知道在比较时应该可以,他们应该是平等的,但我不知道这是什么原因... –
@AhmadF:那是因为有一个“预先分解”和“分解”的字符组合表示,并结合了变音符号。尝试'“Á”.precomposedStringWithCanonicalMapping.getUnicodeCodePoints()'和'“Á”.decomposedStringWithCanonicalMapping.getUnicodeCodePoints()' –