C# txt file to 2D char array | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

C# txt file to 2D char array

I have a text file which looks like this: abc def ghi jkl Now I want to put it in a 2D char array. I thought about a nested for-loop but this works only, when the height and width is the same, i.e. [3,3] or [5,5]. Has someone any idea how to realize this in C# as simple as possible?

9th Apr 2020, 6:25 PM
sno0z3
sno0z3 - avatar
3 Answers
+ 2
Where is your code?
9th Apr 2020, 7:58 PM
JaScript
JaScript - avatar
+ 2
Why I asked where your code is. The problem is that in the "for" loop you confuse rows with columns. The outer loop should be for rows and the inner for columns. The code looks like as follows: int column = 3; int rows = 4; char[,] arr = new char[4,3]; for (int i = 0; i < rows; i++) { string line = Console.ReadLine(); for (int j = 0; j < column; j++) { arr[i, j] = line[j]; } }
10th Apr 2020, 2:31 PM
JaScript
JaScript - avatar
0
Here is what I thought about: int column = 3; int rows = 4; for (int i = 0; i < column; i++) { string line = Console.ReadLine(); for (int j = 0; j < rows; j++) { arr[i, j] = line[j]; } } but that doesn't work, because Index is out of range. And according to my example file above I want to build an 2D array [3,4]
9th Apr 2020, 9:12 PM
sno0z3
sno0z3 - avatar