【问题标题】:How to go through the elements of type string如何遍历字符串类型的元素
【发布时间】:2020-07-09 16:11:18
【问题描述】:

我正在编写一个应该返回重复数的函数。我不明白如何遍历字符串类型的元素。

func countDuplicates(_ s:String) -> Int {
    var duplicates = 0

    for i in s {
        duplicates += 1
    }

    return duplicates
}

【问题讨论】:

  • 你正在浏览 String 的元素。那你有什么问题?
  • 我需要在字符串中查找重复字符
  • 问题中没有尝试的迹象。只需跟踪每个角色的外观即可。
  • @EgorGorskikh 你只是想计算一些重复的字符吗?或者您想具体了解其中哪些是重复的?
  • @pawello2222 统计重复字符数

标签: swift string character


【解决方案1】:

你可以试试:

func countDuplicates(_ s:String) -> Int {
    return s.count - Set(s).count
}

地点:

s.count // total number of characters
Set(s).count // number of unique characters

【讨论】:

    【解决方案2】:

    您无需通过字符串来查找重复项的数量。您可以只减去计数和称为Set 的不重复版本。

    func countDuplicates(_ s: String) -> Int { s.count - Set(s).count) }
    

    注意

    您应该考虑那里可能会有多个重复字符。因此,您需要找到所有重复项,例如通过对相似的分组然后对它们进行计数:

    let duplications = Dictionary(grouping: text, by: {$0}).map { [$0.key: $0.value.count] }
    print(duplications)
    

    如果你愿意,你可以得到重复的总和:

    let totalDuplicationCount = dups.filter {$0.count > 1}.reduce(into: 0) { $0 += $1.count - 1 }
    print(totalDuplicationCount)
    

    【讨论】:

      【解决方案3】:

      如果您想查找重复项的总和,下面的代码可能会有所帮助:

      let text = "HelloooE"
      func numberOfDuplicates(_ s: String) -> Int { s.count - Set(s).count }
      
      print(numberOfDuplicates(text)) //Answer: 3 >> which says one "l" and two "o"s are duplicated.
      

      但如果需要计算重复字符的数量,答案应该是这样的:

      let text = "HelloooE"
      func countOfDuplicateChars(_ s: String) -> Int { s.reduce(into: [:]) {result, word in result[word, default: 0] += 1 }
                                                        .filter { $0.value > 1 }
                                                        .count }
      
      print(countOfDuplicateChars(text)) //Answer: 2 >> which says "l" and "o" are duplicated characters.
      

      下面的函数也是返回重复字符的计数,并且不区分大小写:

      let text = "HelloooE"
      func countOfDuplicateChars_CS(_ s: String) -> Int { s.lowercased()
                                                           .reduce(into: [:]) {result, word in result[word, default: 0] += 1 }
                                                           .filter { $0.value > 1 }
                                                           .count }
      
      print(countOfDuplicateChars(text)) //Answer: 3 >> which says "l", "o" and "e" are duplicated characters.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-29
        • 1970-01-01
        • 2018-11-19
        • 2012-01-13
        • 2018-05-15
        相关资源
        最近更新 更多