gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 05:52:06 24 4
gpt4 key购买 nike

我想按给定大小的 block 拆分字符串 2

示例:

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

最佳答案

您可以按照以下每 n 个元素对您的集合元素(在本例中为字符)进行分组:

extension Collection {
func unfoldSubSequences(limitedTo maxLength: Int) -> UnfoldSequence<SubSequence,Index> {
sequence(state: startIndex) { start in
guard start < self.endIndex else { return nil }
let end = self.index(start, offsetBy: maxLength, limitedBy: self.endIndex) ?? self.endIndex
defer { start = end }
return self[start..<end]
}
}
func subSequences(of n: Int) -> [SubSequence] {
.init(unfoldSubSequences(limitedTo: n))
}
}

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

编辑/更新:

如果您想将超出的字符附加到最后一组:

extension Collection {
func unfoldSubSequencesWithTail(lenght: Int) -> UnfoldSequence<SubSequence,Index> {
let n = count / lenght
var counter = 0
return sequence(state: startIndex) { start in
guard start < endIndex else { return nil }
let end = index(start, offsetBy: lenght, limitedBy: endIndex) ?? endIndex
counter += 1
if counter == n {
defer { start = endIndex }
return self[start...]
} else {
defer { start = end }
return self[start..<end]
}
}
}
func subSequencesWithTail(n: Int) -> [SubSequence] {
.init(unfoldSubSequencesWithTail(lenght: n))
}
}

let numbers = "1234567"
let subSequencesWithTail = numbers.subSequencesWithTail(n: 2)
print(subSequencesWithTail) // ["12", "34", "567"]

关于ios - 如何按给定大小的 block 从字符串拆分为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48088882/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com