如何遍历字符串类型的元素

时间:2020-07-09 16:11:18

标签: swift string character

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

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

    for i in s {
        duplicates += 1
    }

    return duplicates
}

3 个答案:

答案 0 :(得分:1)

您无需遍历字符串即可找到重复项的数量。您只需减去计数和不重复的版本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)

答案 1 :(得分: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 :(得分:1)

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

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.