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

15,010

Solution 1

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.

Solution 2

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();
    }
}

Solution 3

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();
Share:
15,010

Related videos on Youtube

Elmo
Author by

Elmo

Updated on September 14, 2022

Comments

  • Elmo
    Elmo over 1 year

    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?

  • Roman Pekar
    Roman Pekar over 11 years
    +1 nice! But you res is an array of array of length 3, not 2 (two strings and empty string).
  • Keith Jackson
    Keith Jackson about 7 years
    IMO this is the cleanest answer here
  • George
    George almost 6 years
    fantastic solution. Thanks.