-2

An 11 character number will be entered and the middle characters of these 11 characters will be hidden. How can I do that ?

Like this

Ufuk Köşker
  • 1,288
  • 8
  • 29

2 Answers2

2

One of the solutions can be to use the replacingCharacters method:

var someStr = "12345678901"

func replaceMiddle(of text: String, withCharacter character: String, offset: Int) -> String {
    let i1: String.Index = text.index(text.startIndex, offsetBy: offset)
    let i2: String.Index = text.index(text.endIndex, offsetBy: -1 * offset)
    let replacement = String(repeating: character, count: text.count - 2 * offset)
    return text.replacingCharacters(in: i1..<i2, with: replacement)
}

print(replaceMiddle(of: someStr, withCharacter: "*", offset: 3))
// prints "123*****901"
pawello2222
  • 46,897
  • 22
  • 145
  • 209
  • Thank you sir but I want it to change when I write the text. I don't want it to change after I write the text. – Ufuk Köşker Jun 04 '20 at 13:24
  • 1
    Then you can follow this answer: [How do I check when a UITextField changes?](https://stackoverflow.com/questions/28394933/how-do-i-check-when-a-uitextfield-changes) – pawello2222 Jun 04 '20 at 13:30
0

You need to implement the UITextFieldDelegate, then you can use @pawello2222 to generate the replace string

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    var newText = ((textField.text ?? "") as NSString).replacingCharacters(in: range, with: string)

    if NEED_TO_CHANGE_STRING {
        textField.text = NEW_STRING
        return false // Return false to prevent the UITextField to add the new changes since you have just overriten them
    }
    return true // Return true will make the UITextField update automatically
}
rob180
  • 901
  • 1
  • 9
  • 29