stringswiftsplitdivide

Split String into groups with specific length


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 and group length of 3. The the string should be divided into 3 groups: 123, 456, 789. String 1234567 will be divided into 1, 234, 567

So, can you write some nice code in Swift:

func splitedString(string: String, length: Int) -> [String] {

}

BTW tried function split(), but as I understand it works only with finding some symbol


Solution

  • 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..<endIndex])
        }
    
        return result.reverse()
    }
    

    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..<endIndex]
            }
    }