Split String into groups with specific length

后端 未结 10 1778
囚心锁ツ
囚心锁ツ 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 09:59

    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
    

提交回复
热议问题