我正在编写一个应返回重复次数的函数。我不明白如何遍历字符串类型的元素。
func countDuplicates(_ s:String) -> Int {
var duplicates = 0
for i in s {
duplicates += 1
}
return duplicates
}
你可以试试:
func countDuplicates(_ s:String) -> Int {
return s.count - Set(s).count
}
哪里:
s.count // total number of characters
Set(s).count // number of unique characters
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句