如何在 Swift 中将给定的 String
分成具有给定长度的组,从右到左读取?
例如,我有字符串 123456789
,组长度为 3。字符串应分为 3 组:123
、456
, 789
。字符串1234567
会被分成1
、234
、567
那么,你能用 Swift 写一些漂亮的代码吗:
func splitedString(string: String, length: Int) -> [String] {
}
顺便说一句,尝试了函数 split()
,但据我所知,它只适用于找到一些符号
最佳答案
swift 4
我改编了answer given by cafedeichi根据功能参数从左到右或从右到左操作,因此它更加通用。
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..<endIndex]), at: 0)
case false:
let startIndex = self.index(self.startIndex, offsetBy: i)
let endIndex = self.index(startIndex, offsetBy: every, limitedBy: self.endIndex) ?? self.endIndex
result.append(String(self[startIndex..<endIndex]))
}
}
return result
}
}
例子:
"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"]
关于string - 将字符串拆分为特定长度的组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33305157/