字符串分割到多维数组 [英] Split String into Multidimensional Array

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

问题描述

我有这样的:

String s = "abcd,efgh,ijkl";

我想将它转换成这种编程方式:

I want to convert it into this programmatically:

String[,] s = {{"ab","cd"},{"ef","gh"},{"ij","kl"}};

该字符串可以是可变长度的。谁能告诉我,我该怎么办呢?

The string can be of variable length. Can anyone tell me how do I do this?

推荐答案

分裂成的String [] [] 可以这样做:

var res = s.Split(',')
    .Select(p => Regex.Split(p, "(?<=\\G.{2})"))
    .ToArray();

转换为字符串[,] 需要额外的循环:

var twoD = new String[res.Length,res[0].Length];
for (int i = 0 ; i != res.Length ; i++)
    for (int j = 0 ; j != res[0].Length ; j++)
        twoD[i,j] = res[i][j];

二维部分需要通过分隔的所有字符串,是相同的长度。该 RES 数组的数组,在另一方面,可以用参差不齐,即行可以有不同的长度。

The 2D part requires that all strings separated by , be of the same length. The res array of arrays, on the other hand, can be "jagged", i.e. rows could have different lengths.

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

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