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

Swift中如何移除数组元素中的特定子字符串?

Swift实现数组元素批量子串替换

当然可以实现,下面分两种场景给出具体代码:

场景1:仅替换指定子串(得到["House", "House Dog", "House Wife"])

遍历数组,对每个元素执行replacingOccurrences(of:with:)方法,只替换" Dad"子串:

let originalArray = ["House Dad", "House Dog", "House Wife"]
let firstStepArray = originalArray.map {
    $0.replacingOccurrences(of: " Dad", with: "")
}
// firstStepArray 结果:["House", "House Dog", "House Wife"]

场景2:批量移除多个目标子串(最终得到["House", "House", "House"])

有两种常用实现方式:

方式1:多次调用替换方法

对每个元素依次替换所有目标子串:

let finalArray1 = originalArray.map { str in
    str.replacingOccurrences(of: " Dad", with: "")
       .replacingOccurrences(of: " Dog", with: "")
       .replacingOccurrences(of: " Wife", with: "")
}
// finalArray1 结果:["House", "House", "House"]

方式2:正则表达式批量匹配替换

用正则表达式一次性匹配所有要移除的后缀子串,更简洁高效:

import Foundation

let suffixRegex = try! NSRegularExpression(pattern: #" (Dad|Dog|Wife)$"#)
let finalArray2 = originalArray.map { str in
    let range = NSRange(str.startIndex..., in: str)
    return suffixRegex.stringByReplacingMatches(in: str, range: range, withTemplate: "")
}
// finalArray2 结果:["House", "House", "House"]

正则表达式中的$确保只匹配字符串末尾的目标子串,避免误替换中间出现的相同内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 20:17:20