Split String into groups with specific length

后端 未结 10 1770
囚心锁ツ
囚心锁ツ 2021-01-05 09:32

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

10条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-05 10:18

    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"]
    

提交回复
热议问题