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
Swift 4
I adapted the answer given by cafedeichi to operate either left-to-right or right-to-left depending on a function parameter, so it's more versatile.
extension String {
/// Splits a string into groups of `every` n characters, grouping from left-to-right by default. If `backwards` is true, right-to-left.
public func split(every: Int, backwards: Bool = false) -> [String] {
var result = [String]()
for i in stride(from: 0, to: self.count, by: every) {
switch backwards {
case true:
let endIndex = self.index(self.endIndex, offsetBy: -i)
let startIndex = self.index(endIndex, offsetBy: -every, limitedBy: self.startIndex) ?? self.startIndex
result.insert(String(self[startIndex..
Example:
"abcde".split(every: 2) // ["ab", "cd", "e"]
"abcde".split(every: 2, backwards: true) // ["a", "bc", "de"]
"abcde".split(every: 4) // ["abcd", "e"]
"abcde".split(every: 4, backwards: true) // ["a", "bcde"]