在Swift中计算不同的字符

Mar*_*kus 0 string for-loop character swift

我是swift的新手,我正在尝试count不同的characters,string但我的代码返回整个值String

对于例如:

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

counter = 0
let a = "a"

for a in aString.characters {
  counter++
}                                      //equally returns 5
Run Code Online (Sandbox Code Playgroud)

有人可以解释为什么会发生这种情况以及我如何计算不同的字符

Luc*_*tti 15

它看起来对你真正需要的东西有些困惑.

我试图回答5种最可能的解释.

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)
Run Code Online (Sandbox Code Playgroud)


use*_*734 8

检查一下

var aString = "aabb"
aString.characters.count // 4

var counter = 0
let a = "a" // you newer use this in your code 

for thisIsSingleCharacterInStringCharactersView in aString.characters {
    counter++
}
print(counter) // 4
Run Code Online (Sandbox Code Playgroud)

它只是为每个角色增加你的计数器

要计算字符串中不同字符的数量,您可能可以使用"更高级"的内容,如下一个示例所示

let str = "aabbcsdfaewdsrsfdeewraewd"

let dict = str.characters.reduce([:]) { (d, c) -> Dictionary<Character,Int> in
    var d = d
    let i = d[c] ?? 0
    d[c] = i+1
    return d
}
print(dict) // ["b": 2, "a": 4, "w": 3, "r": 2, "c": 1, "s": 3, "f": 2, "e": 4, "d": 4]
Run Code Online (Sandbox Code Playgroud)