算法 – Swift中的字数
发布时间:2020-12-14 02:26:45 所属栏目:百科 来源:网络整理
导读:在 Swift中编写简单的字数统计函数有什么更优雅的方法? //Returns a dictionary of words and frequency they occur in the stringfunc wordCount(s: String) - DictionaryString,Int { var words = s.componentsSeparatedByString(" ") var wordDictionary
在
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]
你的方法非常可靠,但这会带来一些改进.我使用Swifts“if let”关键字存储值计数以检查可选值.然后我可以在更新字典时使用count.我使用updateValue的简写表示法(dict [key] = val).我还在所有空格上分割原始字符串,而不是仅仅一个空格.
func wordCount(s: String) -> Dictionary<String,Int> { var words = s.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) var wordDictionary = Dictionary<String,Int>() for word in words { if let count = wordDictionary[word] { wordDictionary[word] = count + 1 } else { wordDictionary[word] = 1 } } return wordDictionary } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |