Home > Back-end >  String replace digits 0123456789 with X in Swift iOS
String replace digits 0123456789 with X in Swift iOS

Time:06-17

Need to replace phone number list with X and format should stay the same.

For example:

  1. Input-> 201-555-0123 -> Expected Output: XXX-XXX-XXXX
  2. Input-> 612 34 56 78 -> Expected Output: XXX XX XX XX
  3. Input-> 9 11 2345-6789 -> Expected Output: X XX XXXX-XXXX
  4. Input-> 622-1234 -> Expected Output: XXX-XXXX

Can anyone suggest proper way of finding digits 0 to 9 in the string and replace with X.

Tried as below it doesn't finds number and returns same.

func getMaskedNumber(formattedPhoneNumber: String) -> String {
        let maskedNumber = formattedPhoneNumber.replacingOccurrences(of: "[0-9]", with: "X")
        return maskedNumber
}
 numberToDisplay = getMaskedNumber(formattedPhoneNumber: "201-555-0123") // Expected O/P as XXX-XXX-XXXX

CodePudding user response:

You can use regex. Try this:

func getMaskedNumber(formattedPhoneNumber: String) -> String {
    return formattedPhoneNumber.replacingOccurrences(of: "[0-9]", with: "X", options: .regularExpression, range: nil)
}

CodePudding user response:

What about:

func getMaskedNumber(formattedPhoneNumber: String) -> String
{
    var maskedNumber: String

    for digit in 0 ... 9
    {
        maskedNumber = formattedPhoneNumber.replacingOccurrences(of: "\(digit)", with: "X")
    }

    return maskedNumber
}

CodePudding user response:

Create an extension you can reuse and use a regular expression to replace the digits. This extension works for String and Substring:

extension StringProtocol {

    func maskingDigits<Mask>(with mask: Mask) -> String where Mask: StringProtocol {
        replacingOccurrences(
            of: "[0-9]",
            with: mask,
            options: .regularExpression,
            range: nil
        )
    }
}

Usage:

let number = "201-555-0123"
let maskedString = number.maskingDigits(with: "X")
let maskedSubstring = number.prefix(3).maskingDigits(with: "X")

print("Masked String:", maskedString)
print("Masked Substring:", maskedSubstring)

Prints:

Masked String: XXX-XXX-XXXX
Masked Substring: XXX

CodePudding user response:

With Xcode 14 (Swift 5.7) you can use the new Swift evolution proposal SE-0357 Regex-powered string processing algorithms

let numberToDisplay = "201-555-0123".replacing(/\d/, with: "X")
numberToDisplay  // "XXX-XXX-XXXX"
  • Related