John John - 1 year ago 76
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

will output
ABCD 12345

input is
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 Source

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)

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download