Bramble
Bramble

Reputation: 1395

C# text file to 2d array?

If I create a 2d array like so:

int[,] MyArray = new int[5, 5];

and have a text file with these numbers:

1 2 3 4 5

5 4 3 2 1

1 2 3 4 5

2 3 4 6 7

7 8 9 6 4

How do I get the numbers into the 2d array?

Upvotes: 0

Views: 2647

Answers (3)

Leios
Leios

Reputation: 11

string[] line = text.split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < line.Length; i++)
{
    string[] digit = text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    for (int j = 0; j < digit.Length; j++)
    {
        MyArray[i, j] = Convert.ToInt32(digit[j]);
    }
}

Upvotes: 1

John Weldon
John Weldon

Reputation: 40789

However you want...

Basically you have to decide.

Here is a heuristic:

  • Read in the file
  • Parse the numbers
  • Calculate the sizes of the arrays
  • Insert the numbers in the appropriate locations.

Upvotes: 0

Anon.
Anon.

Reputation: 60033

This should be fairly straightforward. Nested loops are the "traditional" way to handle multidimensional arrays.

Nest two loops, the outer iterating over lines in the input, the inner over numbers in a line.

Upvotes: 2

Related Questions