【发布时间】: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
}
它有效。但这似乎过于复杂。有没有更简单和/或更优雅的方法来实现这一点?
【问题讨论】: