Split string into chunks of ranges

I'm trying to write a method to take a string and break it up into an array where each element of the array is the next 10 characters. So a string that's 32 characters long would end up with 3 array elements containing the first 30 characters, and then the 4th array element would have the last 2 characters.


I was trying to use substringWithRange for this but as soon as I advance past the str.endIndex it throws an exception, and I can't figure out how to work around that. I know it's just a silly syntax thing, but I'm stuck.

Accepted Reply

OK, I finally got this working. For anyone else who needs it, or wants to point out a better way to do this, see below. The resolution to the 'beyond the end' problem was to use the limit parameter to advancedBy()



extension String {
    func splitByLength(length: Int) -> [String] {
        var lines: [String] = []
        var start = self.startIndex
        let endIndex = self.endIndex
       
        while start != endIndex {
            let end = start.advancedBy(length, limit: endIndex)
           
            lines.append(self.substringWithRange(start..<end))
           
            start = end
        }
       
        return lines
    }
}

Replies

OK, I finally got this working. For anyone else who needs it, or wants to point out a better way to do this, see below. The resolution to the 'beyond the end' problem was to use the limit parameter to advancedBy()



extension String {
    func splitByLength(length: Int) -> [String] {
        var lines: [String] = []
        var start = self.startIndex
        let endIndex = self.endIndex
       
        while start != endIndex {
            let end = start.advancedBy(length, limit: endIndex)
           
            lines.append(self.substringWithRange(start..<end))
           
            start = end
        }
       
        return lines
    }
}

Irrelevant for the current Swift version as all the methods are deprecated.