【问题标题】:How can I remove duplicate strings from an array and count them in Swift?如何从数组中删除重复的字符串并在 Swift 中计算它们?
【发布时间】:2021-09-08 13:23:05
【问题描述】:

想先打印出重复的字符,然后再打印出下一个字符数。

喜欢从 ["a","a","b","c","c"] 到 ["a", "2","c","2"]。

但是,我没有正确地解决这个问题。希望您就我的代码给我反馈,或者让我知道您的智慧如何解决这个问题。

import Foundation

var m : [String] = ["a","a","b","c","c"]

var count : Int = 0

var result : [String] = []

for i in 0..<m.count{
for word in m {

    if m[i] == word{
        count += 1
        result.append(word)

    }else{
        count = 0
    }
    if count > 1{
       result.append(String(count))
    }
}
}

print("\(count)")
print("\(result)") 
//["a", "a", "2", "a", "a", "2", "b", "c", "c", "2", "c", "c", "2"]


print(["a", "2","c","2"])// want to print it on the console like this.

【问题讨论】:

    标签: arrays count swift5


    【解决方案1】:

    您可以通过以下方法直接获取重复值

    let fiteredValue = arrayList.filterDuplicates(includeElement: {$0 == $1})
    

    【讨论】:

      【解决方案2】:

      它有一个类型,NSCountedSet

      let m = ["a","a","b","c","c"]
      
      let countedSet = NSCountedSet(array: m)
      var result = [String]()
      countedSet.forEach {
         let count = countedSet.count(for: $0)
         if count > 1 {
             result.append(contentsOf: [$0 as! String, String(count)])
         }
      }
      print(result)
      

      【讨论】:

      • 看到您的代码时对一件事感到好奇。让我知道你为什么使用 as!而是作为?
      • NSCountedSet — 与许多 Objective-C 派生类型一样 — 不关心类型,就 Swift 而言,元素是 Any。强制转换是无害的,因为您知道数组只包含字符串。
      猜你喜欢
      • 1970-01-01
      • 2021-03-21
      • 2016-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-15
      相关资源
      最近更新 更多