Converting a delimited string to 2-D array

2019-07-11 14:40发布

I have a grid of two-digit numbers written as a string delimited with newlines and spaces, e.g.:

string grid = "58 96 69 22 \n" +
              "87 54 21 36 \n" +
              "02 26 08 15 \n" +
              "88 09 12 45";

I would like to split it into a 4-by-4 array, so that I can access it via something like separatedGrid[i, j]. I know I can use grid.Split(' ') to separate the numbers in each row, but how do I get a 2-D array out of it?

标签: c# arrays string
2条回答
混吃等死
2楼-- · 2019-07-11 14:43

Yes use split like this:

string grid = "58 96 69 22 \n87 54 21 36 \n02 26 08 15 \n88 09 12 45";

var jagged = grid.Split('\n').Select(
            x => new string[4] { x.Split(' ')[0], x.Split(' ')[1], x.Split(' ')[2], x.Split(' ')[3] }
            ).ToArray();

And if you want a 2-D Array:

var _2D = new String[jagged.Length, jagged[0].Length];
for (var i = 0; i != jagged.Length; i++)
    for (var j = 0; j != jagged[0].Length; j++)
        _2D[i, j] = jagged[i][j];

The result:

enter image description here

查看更多
放我归山
3楼-- · 2019-07-11 14:59

So what you want is to convert a delimited multi-Line String into a 2D-Array:

string grid = "58 96 69 22 \n" +
    "87 54 21 36 \n" +
    "02 26 08 15 \n" +
    "88 09 12 45";

var lines = grid.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries)
                .Select(x => x.Trim().Split(' ')).ToArray();

int numberOfRows = lines.Length;
int maxNumberOfColumns = lines.Max(x => x.Length);
string[,] separatedGrid = new string[numberOfRows, maxNumberOfColumns];

for (int i = 0; i < lines.Count(); i++)
{
    string[] values = lines.ElementAt(i);
    for (int j = 0; j < values.Length; j++)
    {
        separatedGrid.SetValue(values[j], i, j);
    }
}
查看更多
登录 后发表回答