damaren
damaren

Reputation: 23

Replace string subrange with character and maintain length in Swift

I would like to hide sensitive user data in strings by replacing a certain subrange with asterisks. For instance, replace all characters except the first and last three, turning

"sensitive info"

into

"sen********nfo".

I have tried this:

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
}

and it works. But it seems overcomplicated. Is there a simpler and/or more elegant way of achieving this?

Upvotes: 2

Views: 899

Answers (1)

vadian
vadian

Reputation: 285072

How about building the string with the first three characters (prefix(3)) the created asterisk substring and the last three characters (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))
}

Upvotes: 3

Related Questions