Danh Huynh Danh Huynh - 24 days ago 7
Swift Question

Swift 3: split a string to array by number

I have a string

let string = "!101eggs"
. Now, I want to have an array like this
["!", "101", "e", "g", "g", "s"]
. How can I do this?

Answer

Sorry It's too long

when input is

print("-1-2a000+4-1/000!00005gf101eg14g1s46nj3j4b1j5j23jj212j4b2j41234j01010101g0000z00005g0000".toArrayByNumber())

Result: ["-", "1", "-", "2", "a", "000", "+", "4", "-", "1", "/", "000", "!", "00005", "g", "f", "101", "e", "g", "14", "g", "1", "s", "46", "n", "j", "3", "j", "4", "b", "1", "j", "5", "j", "23", "j", "j", "212", "j", "4", "b", "2", "j", "41234", "j", "01010101", "g", "0000", "z", "00005", "g", "0000"]

    extension Int {
    func toZeroString() -> String {
        return (0 ..< self).reduce("", { (result, zero) -> String in
            return result + "0"
        })
    }
}

extension String {

    func toArrayByNumber() -> [String] {

        var array: [String] = []
        var num = 0
        var zeroCount = 0
        var zeroEnd = false

        for char in self.characters {
            if let number = Int("\(char)") {
                if zeroEnd == false && number == 0 {
                    zeroCount += 1
                } else {
                    num = num * 10 + number
                    zeroEnd = true
                }

            } else {
                if num != 0 {
                    array.append(zeroCount.toZeroString() + ("\(num)"))
                } else if zeroCount > 0 {
                    array.append(zeroCount.toZeroString())
                }


                array.append(String(char))
                num = 0
                zeroCount = 0
                zeroEnd = false
            }
        }

        if num != 0 {
            array.append(zeroCount.toZeroString() + ("\(num)"))
        } else if zeroCount > 0 {
            array.append(zeroCount.toZeroString())
        }

        return array
    }
}
Comments