gpt4 book ai didi

arrays - Swift 如何从短语中获取包含字符数的字典

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

我想从一个包含单词和每个单词的字符数的字符串创建一个字典。

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]

如果有人能就此提供任何指导,那就太好了。

谢谢,

最佳答案

首先创建一个空的tupleArray。接下来使用 componentsSeparatedByString 分解您的句子,并使用 forEach 遍历所有元素(单词)以附加该元素($0 = 单词)及其字符计数,后跟一个元组 ("",1)。然后只需使用 popLast 删除那个多余的元组。像这样尝试:

let textToShow = "Try not to become a man of success, but"

var tupleArray:[(String, Int)] = []

textToShow.componentsSeparatedByString(" ")
.forEach{tupleArray += [($0,$0.characters.count),(" ",1)]}
tupleArray.popLast()
print(tupleArray.description) // "[("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)]\n"

关于arrays - Swift 如何从短语中获取包含字符数的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36877458/

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