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
Another solution using substrings:
func splitStringByIntervals(str: String, interval: Int) -> [String] {
let st = String(str.characters.reverse())
let length = st.characters.count
var groups = [String]()
for (var i = 0; i < length; i += interval) {
groups.append((st as NSString).substringWithRange(NSRange(location: i, length: min(interval, length - i))))
}
return groups.map{ String($0.characters.reverse())}.reverse()
}
The output for :
for element in splitStringByIntervals("1234567", interval: 3) {
print(element)
}
is:
1
234
567