Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 316
Elmo Avatar asked Dec 16 '22 18:12

Elmo


2 Answers

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

like image 186
Sergey Kalinichenko Avatar answered Dec 18 '22 08:12

Sergey Kalinichenko


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();
    }
}
like image 26
kernowcode Avatar answered Dec 18 '22 06:12

kernowcode