-2

for my project I want to show credit card numbers on a template.

From my API i get credit card number like "4242424242424242" but i need to reformat this numbers with space like this "4242 4242 4242 4242".

I read some topics but people always explaining with textfield or something like this. I have 16 chars long string variable and i need to reformat this to 19 chars long string with spaces.

I dont need any validation just want to make string with spaces.

As a result i need to turn this string "4242424242424242" to "4242 4242 4242 4242" this string.

Last edit: First of all thank you for all answers, i am sorry for asking questions that already asked.

kemalsanli
  • 39
  • 9

3 Answers3

3

Use replaceingOccurrences(of:with:options:range:) with Regular Expressions:

let creditCardNumber = "4242424242424242"// 16 or 15 digit 
let formattedCreditCardNumber = creditCardNumber.replacingOccurrences(of: "(\\d{4})(\\d{4})(\\d{4})(\\d+)", with: "$1 $2 $3 $4", options: .regularExpression, range: nil)
print(formattedCreditCardNumber)// result 4242 4242 4242 4242

Some UnionPay cards will be 19 digits:

let unionPayCardNumber = "4242424242424242123"
        let formattedUnionPayCardNumber = unionPayCardNumber.replacingOccurrences(of: "(\\d{4})(\\d{4})(\\d{4})(\\d{4})(\\d+)", with: "$1 $2 $3 $4 $5", options: .regularExpression, range: nil)
print(formattedCreditCardNumber)// result 4242 4242 4242 4242 123
Mirzohid Akbarov
  • 1,192
  • 1
  • 10
  • 17
0

Here's one way to do this:

First, split the string into substrings of equal lengths of 4, which can be done with this method found here.

extension String {
    func split(by length: Int) -> [String] {
        var startIndex = self.startIndex
        var results = [Substring]()

        while startIndex < self.endIndex {
            let endIndex = self.index(startIndex, offsetBy: length, limitedBy: self.endIndex) ?? self.endIndex
            results.append(self[startIndex..<endIndex])
            startIndex = endIndex
        }

        return results.map { String($0) }
    }
}

And then, you can join the split parts with your desired separator:

extension String {

    func inserting(_ c: Character, every index: Int) -> String {
        return self.split(by: index).joined(separator: c)
    }
}

Usage:

let formatted = yourString.inserting(" ", every: 4)
Sweeper
  • 213,210
  • 22
  • 193
  • 313
-3

This should work. It is not particularly expandable though.

let before = "4242424242424242"
let after = "\(before[0..<4]) \(before[4..<8]) \(before[8..<12]) \(before[12..<16])"
Benjamin Davies
  • 353
  • 1
  • 13