我是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
有人可以解释为什么会发生这种情况以及我如何计算不同的字符?
它看起来对你真正需要的东西有些困惑.
我试图回答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)
检查一下
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
它只是为每个角色增加你的计数器
要计算字符串中不同字符的数量,您可能可以使用"更高级"的内容,如下一个示例所示
let str = "aabbcsdfaewdsrsfdeewraewd" let dict = str.characters.reduce([:]) { (d, c) -> Dictionaryin 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]