gpt4 book ai didi

swift - 如何使用元组计算子字符串(单词)在字符串中出现的次数

转载 作者:搜寻专家 更新时间:2023-11-01 06:34:09 28 4
gpt4 key购买 nike

给定一个存储在变量字符串中的字符串数组。创建一个名为 countedStrings 的新数组,其中包含类型为 (String, Int) 的值。每个元组包含一个来自字符串数组的字符串,后跟一个整数,指示它在字符串数组中出现的次数。每个字符串在 countedStrings 数组中应该只出现一次。

我没有解决这个问题,因为它已经解决了。我只是想了解它。它的一部分我能理解,有些部分我不能。我无法理解 for 循环中的部分。

 var a =  ["tuples", "are", "awesome", "tuples", "are", "cool","tuples",  "tuples", "tuples", "shades"]

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

for z in a{
var x = false

for i in 0..<y.count {
if (y[i].0 == z) {
y[i].1 += 1
x = true
}
}
if x == false {
y.append((z,1))
}
}
print(y)

打印

[("tuples", 5), ("are", 2), ("awesome", 1), ("cool", 1), ("shades", 1)] cool", 1), ("shades", 1)]

最佳答案

如果您遇到这样的问题,请先尝试重命名变量。这对理解问题有很大帮助。

例如,我采用了您的代码,只是为了清楚起见更改了变量名称。现在告诉我您是否还有什么不明白的地方。

let words = ["tuples", "are", "awesome", "tuples", "are", "cool","tuples",  "tuples", "tuples", "shades"]

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

for word in words {
var isAlreadyInTupleArray = false

// Loop trough the existing tuples and updates the number of apparition if the word is found
for (index, tuple) in tuples.enumerated() {
let tupleWord:String = tuple.0
let numberOfAppearances:Int = tuple.1

if tupleWord == word {
tuples[index].1 += 1

isAlreadyInTupleArray = true
}
}

// In the case the word was not in the existing tuples, we append a new tuple
if isAlreadyInTupleArray == false {
tuples.append((word, 1))
}
}
print(tuples)

关于swift - 如何使用元组计算子字符串(单词)在字符串中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43538896/

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