简体   繁体   中英

How do I split a string into a Multidimensional or a Jagged Array?

I have this:

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?

Do this

using System.Linq;

var s = "ab,cd;ef,gh;ij,kl";
var a = s.Split(';').Select(x=>x.Split(',')).ToArray()

or extension method

var a = "ab,cd;ef,gh;ij,kl".ToTwoDimArray();

public static class StringExtentions
{
    public static string[][] ToTwoDimArray(this string source, char separatorOuter = ';', char separatorInner = ',')
    {
        return source
               .Split(separatorOuter)
               .Select(x => x.Split(separatorInner))
               .ToArray();
    }
}

Splitting into String[][] can be done like this:

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

Converting to String[,] requires an additional loop:

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];

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", ie rows could have different lengths.

you can do it with LINQ

 s.Split(',').Select(
             x => new string[2] { x.Substring(0, 2), x.Substring(2, 2)}
 ).ToArray();

or you can just go with cycle

        String s = "abcd,efgh,ijkl";
        var l = new List<string[]>();
        for (int i = 0; i < s.Length; i += 5)
            l.Add(new string[2] { s.Substring(i, 2), s.Substring(i + 2, 2) });

        String[][] sa = l.ToArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM