【问题标题】:Replace string subrange with character and maintain length in Swift用字符替换字符串子范围并在 Swift 中保持长度
【发布时间】:2020-11-04 15:55:08
【问题描述】:

我想通过用星号替换某个子范围来隐藏字符串中的敏感用户数据。比如替换除前三个和后三个以外的所有字符,转

“敏感信息”

进入

“森********信息”。

我试过这个:

func hideInfo(sensitiveInfo: String) -> String {
  let fIndex = sensitiveInfo.index(sensitiveInfo.endIndex, offsetBy: -4)
  let sIndex = sensitiveInfo.index(sensitiveInfo.startIndex, offsetBy: 3)
  var hiddenInfo = sensitiveInfo
  let hiddenSubstring = String(repeating: "*", count: hiddenInfo.count - 6)
  hiddenInfo.replaceSubrange(sIndex...fIndex, with: hiddenSubstring)
  return hiddenInfo
}

它有效。但这似乎过于复杂。有没有更简单和/或更优雅的方法来实现这一点?

【问题讨论】:

    标签: swift string replace


    【解决方案1】:

    如何用前三个字符 (prefix(3)) 创建的星号子字符串和后三个字符 (suffix(3)) 构建字符串

    func hideInfo(sensitiveInfo: String) -> String {
        let length = sensitiveInfo.utf8.count
        if length <= 6 { return sensitiveInfo }
        return  String(sensitiveInfo.prefix(3) + String(repeating: "*", count: length - 6) + sensitiveInfo.suffix(3))
    }
    

    【讨论】:

    • 是的,好多了。谢谢!
    • 为什么使用sensitiveInfo.utf8.count 而不是sensitiveInfo.count?
    猜你喜欢
    • 2012-12-05
    • 1970-01-01
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 2017-07-17
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多