Batoul
Batoul

Reputation: 3

retrieving data into a 2D array in C#

I have a text file that has:

1 2 3 4 0 5 6 7 8

How do I show the data in a 2D array of size [3,3]?

I'm new to C# and any help would be great!

I've tried the code below but it doesn't work:

int i = 0, j = 0;
int[,] result = new int[3, 3];
foreach (var row in input.Split('\n'))
{
    j = 0;
    foreach (var col in row.Trim().Split(' '))
    {
        result[i, j] = int.Parse(col.Trim());
        j++;
    }
    i++;
}

Console.WriteLine(result);

Upvotes: 0

Views: 49

Answers (2)

Miq
Miq

Reputation: 4279

divide by 3 and convert to integer to get row, use modulo 3 to get col.

 j=0;
 foreach (var col in input.Trim().Split(' '))
    {
        result[j/3, j%3] = int.Parse(col.Trim());
        j++;
    }

Upvotes: 2

kajacx
kajacx

Reputation: 12939

If all your 9 numbers are on the same line, then splitting by new line will not help. You can do:

foreach (var num in input.Split(' '))
{
    result[i / 3, i % 3] = int.Parse(num.Trim());
    i++;
}

because:

i    i / 3 (div)    i % 3 (mod)
0    0              0
1    0              1
2    0              2
3    1              0
4    1              1
5    1              2
6    2              0
7    2              1
8    2              2

Upvotes: 1

Related Questions