gpt4 book ai didi

swift - 如何根据字符串的出现次数对数组进行排序?

转载 作者:搜寻专家 更新时间:2023-11-01 05:47:24 25 4
gpt4 key购买 nike

如何根据字符串出现的次数对数组进行排序

例子: var array = ["你好","我","那个","我","你好","我","as","the"]

排序后的数组应该是这样的

[“我”,“你好”,“那个”,“作为”,“那个”]

最佳答案

针对 Swift 3 进行了更新

var array = ["Hello","Me","That","Me","Hello","Me","as","the"]

var counts:[String:Int] = [:]

for item in array {
counts[item] = (counts[item] ?? 0) + 1
}
print(counts)

let result = counts.sorted { $0.value > $1.value }.map { $0.key }
print(result)

array.removeAll()
for string in result {
array.append(string)
}
print(array)

关于swift - 如何根据字符串的出现次数对数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42267629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com