John John - 5 months ago 13
Swift Question

Add spacing between digits and non digits

Hi guys I have a probelm that I needed to solve. Here are the examples:

input is

ABCD12345
will output
ABCD 12345


input is
A12345BCDE
will output
A 12345 BCDE


imput is
ABC 12345
will output
ABC 12345
(excess spacing removed)

As shown above a single spacing shall be added when there are no spacing but if there is, it will check if there are double spaces, then it will make it into single spacing.

tx2 tx2
Answer

To accomplish what you ask you can do something like this:

let letters = NSCharacterSet.letterCharacterSet()
let digits = NSCharacterSet.decimalDigitCharacterSet()
var res = ""
var lastDigit = false
for char in [input].unicodeScalars {
    if letters.longCharacterIsMember(char.value) && lastDigit {
        res += " "
        lastDigit = false
    } else if digits.longCharacterIsMember(char.value) && !lastDigit {
        res += " "
        lastDigit = true
    }
    if String(char) != " " {
        res += String(char)
    }
}
print(res)

In the code above you should replace the [input] placeholder with the input that you want to deal and the result string will be in res variable.

Comments