将字符串拆分为数组 [英] Split string into Array of Arrays

查看:146
本文介绍了将字符串拆分为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Swift 4.2

来自服务器的响应是一个字符串,其值由竖线字符"|"分隔.它包含许多行的值.我想将其拆分为子数组.

Response from server is a string with values separated by pipe character "|". It contains many rows of values. I want to split it into an array of subarrays.

响应示例:

"001 |苹果|红色| 002 |香蕉|黄色| 003 |葡萄|紫色"

"001|apple|red|002|banana|yellow|003|grapes|purple"

在此示例中,输出应为包含上述水果的3个数组的数组.如果我使用response.componentsSeparatedByString("|"),它将给我一个包含9个元素的数组,这是我不想要的.如果考虑以上示例,我需要的是一个由3个数组组成的数组,其中还包含3个元素.

For this example, the output should be an array containing 3 arrays of above fruits. If I use response.componentsSeparatedByString("|") it will give me an array with 9 elements, which I don't want. If I take the above example into consideration, what I need is an array of 3 arrays further having 3 elements.

预期输出:

[[001, "apple", "red"], [002, "banana", "yellow"], [003, "grapes", "purple"]]

推荐答案

如果我正确地得到了您想要的结果,那么这段代码将满足您的要求:

If I got correct what you want to receive as a result, then this code would make what you want:

extension Array {
    func chunked(into size: Int) -> [[Element]] {
        return stride(from: 0, to: self.count, by: size).map {
            Array(self[$0 ..< Swift.min($0 + size, self.count)])
        }
    }
}

let src = "001|apple|red|002|banana|yellow|003|grapes|purple"
let result = src.split(separator: "|").map(String.init).chunked(into: 3)
// result = [["001", "apple", "red"], ["002", "banana", "yellow"], ["003", "grapes", "purple"]]

如果您知道结果子数组的预期大小,这将起作用

This will work if you know the expected size of resulting subarrays

如果可以确定数组元素的类型为String.SubSequence

You can also remove .map(String.init) from the last line if it's ok for you that array elements are of type String.SubSequence

这篇关于将字符串拆分为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆