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

如何将Swift字符串指定字符移除逻辑封装为可复用Extension

Swift String 移除指定字符扩展实现方案

你可以给String添加两个扩展方法,分别覆盖原地修改、返回新字符串两种常用场景:

extension String {
    /// 原地移除当前字符串中属于指定字符集合的所有字符
    mutating func removeCharacters(in characterSet: Set<Character>) {
        removeAll(where: { characterSet.contains($0) })
    }
    
    /// 生成并返回移除了指定字符集合中所有字符的新字符串
    func removingCharacters(in characterSet: Set<Character>) -> String {
        self.filter { !characterSet.contains($0) }
    }
}

使用示例

对应你原有的业务逻辑,调用方式如下:

var string = "11224B"
let removeCharacters: Set<Character> = [" ", ";", ".", "!", "/"]
// 原地修改原字符串
string.removeCharacters(in: removeCharacters)
print(string)

如果不需要修改原字符串,可以调用返回新实例的方法:

let rawString = "test/string! with space;"
let cleanedString = rawString.removingCharacters(in: [" ", ";", ".", "!", "/"])
// cleanedString 结果为 "teststringwithspace",rawString 保持不变
  • 额外优化提示:如果项目中有固定要移除的字符集合,可以额外封装便捷方法减少重复传参:
extension String {
    mutating func removeCommonSpecialCharacters() {
        self.removeCharacters(in: [" ", ";", ".", "!", "/"])
    }
}

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 13:06:01