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

如何用for-in/forEach实现灵活的Swift字符串字符替换函数

Swift 实现灵活的字符串字符替换函数

需求说明

实现一个接收字符串的函数,将指定字母替换为对应符号:

  • a/A → @
  • i → 1
  • s → $
  • o → 0
  • t → +
    要求使用 for-in 或 forEach 方法实现,替代不够灵活的链式调用方案。

用户现有简单实现

func replaceOld(characters: String) -> String {
    let newChars = characters.replacingOccurrences(of: "a", with: "@")
                             .replacingOccurrences(of: "i", with: "1")
                             .replacingOccurrences(of: "s", with: "$")
                             .replacingOccurrences(of: "o", with: "0")
                             .replacingOccurrences(of: "t", with: "+")
    return newChars
}
replaceOld(characters: "Swift is awesome")

执行输出:Sw1f+ 1$ @we$0me

灵活版实现方案

利用替换规则数组,通过循环遍历完成批量替换,后续修改规则只需调整数组即可:

方案1:使用 for-in 循环

func replaceChars(characters: String) -> String {
    // 定义替换规则,包含大小写a的替换
    let replacementRules = [
        ("a", "@"),
        ("A", "@"),
        ("i", "1"),
        ("s", "$"),
        ("o", "0"),
        ("t", "+")
    ]
    
    var result = characters
    // 遍历规则数组,逐次替换
    for (targetChar, replacement) in replacementRules {
        result = result.replacingOccurrences(of: targetChar, with: replacement)
    }
    return result
}

// 测试示例
print(replaceChars(characters: "Swift is awesome")) // 输出: Sw1f+ 1$ @we$0me
print(replaceChars(characters: "Apple Iphone Test")) // 输出: @pple 1ph0ne +es+

方案2:使用 forEach 方法

func replaceChars(characters: String) -> String {
    let replacementRules = [
        ("a", "@"),
        ("A", "@"),
        ("i", "1"),
        ("s", "$"),
        ("o", "0"),
        ("t", "+")
    ]
    
    var result = characters
    replacementRules.forEach { target, replacement in
        result = result.replacingOccurrences(of: target, with: replacement)
    }
    return result
}

方案优势

相比链式调用的版本,循环方案的灵活性大幅提升:

  • 新增/修改替换规则时,只需调整 replacementRules 数组,无需修改多行链式调用代码
  • 规则集中管理,可读性和维护性更强

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 19:35:28