我是 swift 的新手,我正在尝试 count
string
中的不同 characters
但我的代码返回了整个值字符串
例如:
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)
关于string - 在 Swift 中计算不同的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34371495/