Split String into groups with specific length

后端 未结 10 1879
囚心锁ツ
囚心锁ツ 2021-01-05 09:32

How can I split the given String in Swift into groups with given length, reading from right to left?

For example, I have string 123456789 a

10条回答
  •  误落风尘
    2021-01-05 10:00

    I made something like this, couldn't create anything better looking, but its result matches the question:

    func splitedString(string: String, lenght: Int) -> [String] {
        var result = [String](), count = 0, line = ""
        for c in string.characters.reverse() {
            count++; line.append(c)
            if count == lenght {count = 0; result.append(String(line.characters.reverse())); line = ""}
        }
        if !line.isEmpty {result.append(String(line.characters.reverse()))}
        return result.reverse()
    }
    

提交回复
热议问题