Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift iOS Mask a string "Hello" to "Hxxxo"

Tags:

string

ios

swift

extension String {
    var masked: String {
        // some logic which I have to write to mask string.

        // I tried following and just shows x 🤦‍♂️
        // replacingOccurrences(
        //      of: ".(.+).", 
        //      with: "x", 
        //      options: .regularExpression, 
        //      range: nil
        //)
    }
}
let helloWorld = "Hello World"
print("Masked string is - \(helloWorld.masked)")

Expected output is - "Hxxxxxxxxxd"

like image 660
Sagar Kothari Avatar asked May 03 '20 04:05

Sagar Kothari


3 Answers

There is a Regular Expression way with lookaround

extension String {
    var masked: String {
        replacingOccurrences(
            of: "(?!^).(?!$)", // RegEx
            with: "x", // Replacement
            options: .regularExpression // Option to set RegEx
        )
    }
}
like image 158
vadian Avatar answered Oct 22 '22 14:10

vadian


You can enumerate the string and apply map transform to get the expected output:

extension String {
  var masked: String {
    self.enumerated().map({ (index, ch) in
      if index == 0
        || index == self.count - 1 {
        return String(ch)
      }
      return "x"
    }).joined()
  }
}

let str = "hello"
print("after masking \(str.masked)") // Output - hxxxo

The map transform will return an array, so use joined() to convert the array back to String. Also, note that you have to typecast ch to String as String(ch) because the type of ch is 'String.Element' (aka 'Character').

like image 40
sats Avatar answered Oct 22 '22 15:10

sats


extension Sequence {
  func replacingEachInteriorElement(with replacement: Element) -> [Element] {
    let prefix = dropLast()
    return
      prefix.prefix(1)
      + prefix.dropFirst().map { _ in replacement }
      + suffix(1)
  }
}
extension String {
  var masked: Self {
    .init( replacingEachInteriorElement(with: "x") )
  }
}
"Hello World".masked == "Hxxxxxxxxxd" // true
"H🦾👄🐺🥻🐸🦈🏄‍♂️🍯🪐d".masked == "Hello World".masked // true
"🥮".masked // 🥮
"🥶😎".masked // 🥶😎
[].replacingEachInteriorElement(with: 500) // []
like image 3
Jessy Avatar answered Oct 22 '22 14:10

Jessy