Split String into groups with specific length

后端 未结 10 1771
囚心锁ツ
囚心锁ツ 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:19

    Swift 4

    I think the extension method is more useful.

    extension String{
    
        public func splitedBy(length: Int) -> [String] {
    
            var result = [String]()
    
            for i in stride(from: 0, to: self.characters.count, by: length) {
                let endIndex = self.index(self.endIndex, offsetBy: -i)
                let startIndex = self.index(endIndex, offsetBy: -length, limitedBy: self.startIndex) ?? self.startIndex
                result.append(String(self[startIndex..

    the example of use:

    Swift.debugPrint("123456789".splitedBy(length: 4))
    // Returned ["1", "2345", "6789"]
    

提交回复
热议问题