ekkeee
ekkeee

Reputation: 137

How to go through the elements of type string

I am writing a function that should return the number of duplicates. I can’t understand how to go through the elements of type string.

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

    for i in s {
        duplicates += 1
    }

    return duplicates
}

Upvotes: 1

Views: 135

Answers (3)

Amin
Amin

Reputation: 36

If you want to find the total sum of duplicates, the code below could be helpful:

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.

But if the count of duplicated characters is required, this should be the answer:

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.

The function below is also return the count of duplicated characters and also is case insensitive:

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.

Upvotes: 2

Mojtaba Hosseini
Mojtaba Hosseini

Reputation: 119360

You don't need to go through the string to find the count of the duplicates. you can just subtract the count and the not duplicated version called Set.

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

Note

You should consider maybe there will be more than one duplicated character there. So you need to find all duplicates for example by grouping similar and then count them:

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

You can get the sum of the duplicated ones if you want:

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

Upvotes: 1

pawello2222
pawello2222

Reputation: 54516

You can try:

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

Where:

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

Upvotes: 1

Related Questions