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

标签 swift

给定一个存储在变量字符串中的字符串数组。创建一个名为 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/

相关文章:

swift - 如何快速连接字符串中的 "+"运算符

ios - 如果快速填充文本字段,则启用按钮

ios - 如果图像实际上是从 url 下载的,我如何在 swift 5 中知道?

swift - 编辑 SKSpriteNode 自定义类的属性?

ios - 无效的 Swift 支持 - 此位置没有正确的文件类型 (Swift 2.3/Xcode 7.3.1)

swift - Spritekit 禁用特定 View 区域的触摸

ios - "Command failed due to signal: Segmentation fault: 11"- 问题是什么?

使用 Swift 时提前释放 Objective-C 变量

json - 带有 URLSession 的 Swift 中的 SendGrid API 请求

ios - Xcode 7.1 中的共享扩展错误