例如,我想要数组
["ABC", "ADE", "BCD", "HYD", "ZYX", "ZZZ"]
转换为:
[
["ABC", "ADE"],
["BCD"],
["HYD"],
["ZYX", "ZZZ"],
]
那我怎么能做到这一点?谢谢!
答案 0 :(得分:4)
使用你的数组创建一个中间字典,将首字母映射到以该字母开头的字符串数组,然后从字典中创建最终数组:
let arr = ["ABC", "ADE", "BCD", "HYD", "ZYX", "ZZZ"]
var dict = [Character:[String]]()
for str in arr {
if let first = str.characters.first {
dict[first] = (dict[first] ?? []) + [str]
}
}
print(dict) // ["H": ["HYD"], "B": ["BCD"], "A": ["ABC", "ADE"], "Z": ["ZYX", "ZZZ"]]
let arr2 = dict.keys.sort().map { dict[$0]! }
print(arr2) // [["ABC", "ADE"], ["BCD"], ["HYD"], ["ZYX", "ZZZ"]]