我正在嘗試按字母順序對包含許多特殊 Unicode 字符的非英語字串陣列進行排序。我可以創建一個包含所需字典排序順序的 CharacterSet 序列。
Swift5 中是否有執行這種自定義排序的方法?我相信幾年前我就看到過這樣的功能,但今天進行了相當詳盡的搜索,但沒有發現任何問題。
任何指標將不勝感激!
uj5u.com熱心網友回復:
作為 matt 的 cosorting 注釋的簡單實作:
// You have `t` twice in your string; I've removed the first one.
let alphabet = "?jiy?wbpfmnRrlh???zs?qkgt?d? "
// Map characters to their location in the string as integers
let order = Dictionary(uniqueKeysWithValues: zip(alphabet, 0...))
// Make the alphabet backwards as a test string
let string = alphabet.reversed()
// This sorts unknown characters at the end. Or you could throw instead.
let sorted = string.sorted { order[$0] ?? .max < order[$1] ?? .max }
print(sorted)
uj5u.com熱心網友回復:
您可以考慮本地化比較,而不是構建自己的“非英語”排序。例如:
let strings = ["a", "á", "?", "b", "c", "d", "e", "é", "f", "r", "s", "?", "t"]
let result1 = strings.sorted()
print(result1) // ["a", "b", "c", "d", "e", "f", "r", "s", "t", "?", "á", "?", "é"]
let result2 = strings.sorted {
$0.localizedCaseInsensitiveCompare($1) == .orderedAscending
}
print(result2) // ["a", "á", "?", "b", "c", "d", "e", "é", "f", "r", "s", "?", "t"]
let locale = Locale(identifier: "sv")
let result3 = strings.sorted {
$0.compare($1, options: .caseInsensitive, locale: locale) == .orderedAscending
}
print(result3) // ["a", "á", "b", "c", "d", "e", "é", "f", "r", "s", "?", "t", "?"]
還有一個非拉丁語的例子:
let strings = ["あ", "か", "さ", "た", "い", "き", "し", "ち", "う", "く", "す", "つ", "ア", "カ", "サ", "タ", "イ", "キ", "シ", "チ", "ウ", "ク", "ス", "ツ", "が", "ぎ"]
let result4 = strings.sorted {
$0.localizedCaseInsensitiveCompare($1) == .orderedAscending
}
print(result4) // ["あ", "ア", "い", "イ", "う", "ウ", "か", "カ", "が", "き", "キ", "ぎ", "く", "ク", "さ", "サ", "し", "シ", "す", "ス", "た", "タ", "ち", "チ", "つ", "ツ"]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/491469.html
