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
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..