gpt4 book ai didi

algorithm - Swift 中的字数统计

转载 作者:搜寻专家 更新时间:2023-10-30 22:26:39 25 4
gpt4 key购买 nike

<分区>

用 Swift 编写简单的字数统计函数的更优雅的方法是什么?

//Returns a dictionary of words and frequency they occur in the string
func wordCount(s: String) -> Dictionary<String, Int> {
var words = s.componentsSeparatedByString(" ")
var wordDictionary = Dictionary<String, Int>()
for word in words {
if wordDictionary[word] == nil {
wordDictionary[word] = 1
} else {
wordDictionary.updateValue(wordDictionary[word]! + 1, forKey: word)
}
}
return wordDictionary
}

wordCount("foo foo foo bar")
// Returns => ["foo": 3, "bar": 1]

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