Split String into groups with specific length

后端 未结 10 1767
囚心锁ツ
囚心锁ツ 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:04

    Just to add my entry to this very crowded contest (SwiftStub):

    func splitedString(string: String, length: Int) -> [String] {
        var result = [String]()
    
        for var i = 0; i < string.characters.count; i += length {
            let endIndex = string.endIndex.advancedBy(-i)
            let startIndex = endIndex.advancedBy(-length, limit: string.startIndex)
            result.append(string[startIndex..

    Or if you are feeling functional-y:

    func splitedString2(string: String, length: Int) -> [String] {
        return 0.stride(to: string.characters.count, by: length)
            .reverse()
            .map {
                i -> String in
                let endIndex = string.endIndex.advancedBy(-i)
                let startIndex = endIndex.advancedBy(-length, limit: string.startIndex)
                return string[startIndex..

提交回复
热议问题