0

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);
3
  • 1
    What do you mean by it doesn't work? Commented Nov 30, 2019 at 17:11
  • You might want to pass StringSplitOptions.RemoveEmptyEntries as a second parameter to Split() method. Commented Nov 30, 2019 at 17:15
  • In your example it looks like the file contains 9 numbers in one single row, but your code assumes the file to contains 3 rows with three numbers each. Commented Nov 30, 2019 at 17:22

2 Answers 2

2

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++;
    }
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.