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()' –