Swift中能否统计字符串中指定字符的数量?以逗号统计为例
在Swift中统计字符串指定字符的出现次数
当然可以实现,以下是几种常用的原生方法来统计示例字符串 "100,101,305,222" 中逗号的出现次数:
方法1:使用 filter + count(最简洁)
通过filter筛选出所有目标字符,再用count获取数量:
let targetString = "100,101,305,222" let commaCount = targetString.filter { $0 == "," }.count print(commaCount) // 输出:3
方法2:使用 reduce 累加计数
利用reduce的累加特性,遍历字符时统计目标字符的数量:
let targetString = "100,101,305,222" let commaCount = targetString.reduce(0) { accumulator, char in char == "," ? accumulator + 1 : accumulator } print(commaCount) // 输出:3
也可以简化为一行闭包写法:
let commaCount = targetString.reduce(0) { $1 == "," ? $0 + 1 : $0 }
方法3:直接循环遍历计数
最直观的遍历方式,适合理解底层逻辑:
let targetString = "100,101,305,222" var commaCount = 0 for char in targetString { if char == "," { commaCount += 1 } } print(commaCount) // 输出:3
以上方法均基于Swift标准库实现,无需额外引入第三方框架,可根据实际场景选择使用。
内容的提问来源于stack exchange,提问作者schmale96
相关产品推荐
相关产品推荐

