[SOLVED] Counting different Characters in Swift

Issue

I am new to swift and I am trying to count the different characters in a string but my code returns the value for the whole String

for example:

var string aString = "aabb"
aString.characters.count()             //returns 5

counter = 0
let a = "a"

for a in aString.characters {
  counter++
}                                      //equally returns 5

Can somebody explain why this is happening and how I could count the different chars?

Solution

It looks there is some confusion about what you really need.

I tried to answer to the 5 most likely interpretations.

var word = "aabb"

let numberOfChars = word.characters.count // 4
let numberOfDistinctChars = Set(word.characters).count // 2
let occurrenciesOfA = word.characters.filter { $0 == "A" }.count // 0
let occurrenciesOfa = word.characters.filter { $0 == "a" }.count // 2
let occurrenciesOfACaseInsensitive = word.characters.filter { $0 == "A" || $0 == "a" }.count // 2

print(occurrenciesOfA)
print(occurrenciesOfa)
print(occurrenciesOfACaseInsensitive)

Answered By – Luca Angeletti

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.