我想從字符串中創建一個字典,每個字的字符數。Swift如何從短語中得到一個帶字符數的字典
var textToShow:String = "Try not to become a man of success, but" //rather try to become a man of value. Albert Einstein"
print(charactersCount(textToShow))
func charactersCount(s: String) -> Dictionary<String, Int> {
var words = s.componentsSeparatedByString(" ")
var characterInWordDictionary = Dictionary<String, Int>()
for word in words {
characterInWordDictionary[word] = word.characters.count
}
return characterInWordDictionary
}
的問題是,這種梅索德,它返回
["Try": 3, "not": 3, "a": 1, "become": 6, "of": 2, "but": 3, "man": 3, "to": 2, "success,": 8]
它並沒有那麼糟糕,但: - 第一,字典是不是在正確的順序 - 第二,我會就像字典裏的空間一樣。
我想回的是:
["Try": 3, " ": 1, "not": 3, " ": 1, "to": 2, " ": 1, "become": 6, " ": 1, "a": 1, " ": 1, "man": 3, " ": 1, "of": 2, " ": 1, "success,": 8, " ": 1, "but": 3]
如果任何人都可以提供這方面的任何指導,這將是驚人的。
韓國社交協會,
字典沒有順序。你需要一個元組數組 –
字典是無序集合,所以你正在尋找的可能是一個元組''(String,Int)'而不是一個字典的數組。 – dfri