小编典典

如何按给定大小的块从字符串拆分为数组

swift

我想按给定大小的块分割字符串 2

范例:

字符串"1234567"和输出应为["12", "34", "56","7"]


阅读 269

收藏
2020-07-07

共1个答案

小编典典

您可以每隔n个元素对集合元素(在本例中为Characters)进行分组,如下所示:

extension Collection {
    func groups(of n: Int) -> [SubSequence] {
        var startIndex = indices.startIndex
        var groups: [SubSequence] = []
        while startIndex < endIndex {
            let endIndex = indices.index(startIndex, offsetBy: n, limitedBy: indices.endIndex) ?? indices.endIndex
            groups.append(self[startIndex..<endIndex])
            startIndex = endIndex
        }
        return groups
    }
}

let numbers = "1234567"
let groups = numbers.groups(of: 2)
print(groups)    // ["12", "34", "56", "7"]

编辑/更新

如果要将超出的字符追加到最后一组:

extension Collection {
    func groups(of n: Int) -> [SubSequence] {
        var startIndex = self.startIndex
        let count = self.count
        return (0..<count/n).map { _ in
            var endIndex = index(startIndex, offsetBy: n, limitedBy: self.endIndex) ?? self.endIndex
            if count % n > 0, distance(from: self.startIndex, to: startIndex) > (count / n) {
                endIndex = self.endIndex
            }
            defer { startIndex = endIndex }
            return self[startIndex..<endIndex]
        }
    }
}

let numbers = "1234567"
let groups = numbers.groups(of: 2)
print(groups)    // ["12", "34", "567"]
2020-07-07