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?
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With