You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 11:03:15