如何通过给定大小的块从字符串拆分到数组 [英] How can split from string to array by chunks of given size
问题描述
我想按给定大小的块分割字符串 2
I want to split string by chunks of given size 2
示例:
String 1234567
并且输出应为 [12,34,56, 7]
String "1234567"
and output should be ["12", "34", "56","7"]
推荐答案
您可以将字符串转换为字符数组并使用 stride(from:,to:,by:)
方法迭代你的角色每n个元素并使用map返回它们:
You can convert your string into an array of characters and use stride(from:, to:, by:)
method to iterate your characters every n elements and return them using map:
extension String {
func group(of n: Int) -> [String] {
let chars = Array(self)
return stride(from: 0, to: chars.count, by: n).map {
String(chars[$0..<min($0+n, chars.count)])
}
}
}
let numbers = "1234567"
let grouped = numbers.group(of: 2)
print(grouped) // ["12", "34", "56", "7"]
编辑/更新:
如果您想将最后一组字符附加到结果数组的最后一个元素您需要检查结果数组中是否有最后一个元素,并且在将每个元素附加到结果之前,每个字符串字符数是否小于组大小:
If you would like to append the last group of characters to the last element of your resulting array you would need to check if there is a last element in the resulting array and if each string characters count is shorter than the group size before appending each element to the result:
extension String {
func group(of n: Int) -> [String] {
let chars = Array(self)
var result: [String] = []
stride(from: 0, to: chars.count, by: n).forEach {
let string = String(chars[$0..<min($0+n, chars.count)])
if let last = result.last, string.count < n {
result[result.count-1] = last + string
} else {
result.append(string)
}
}
return result
}
}
let numbers = "1234567"
let grouped = numbers.group(of: 2)
print(grouped) // ["12", "34", "567"]
这篇关于如何通过给定大小的块从字符串拆分到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!