简体   繁体   中英

C#: Read a text file into a 2D char array

Like I mentioned above, I try to read a text file into a 2D char array. That's my file:

abcde
fghij
klmno
pqrst
uvwxy

and that's my code:

var path = @"C:text.file";
        StreamReader sr = File.OpenText(path);
        {



            char[,] arr = new char[5, 5];

            for (int i = 0; i < 5; i++)
              {
                  for (int j = 0; j < 5; j++)
                  {
                    arr[i, j] = (Char)sr.Read();
                   Console.WriteLine(arr[i, j] + " = {0},{1}", i,j);
                  }
              }

            Console.WriteLine(arr[2,1]);
        }
    }

and at least my output:

1 = 0,0
2 = 0,1
3 = 0,2
4 = 0,3
5 = 0,4
 = 1,0

 = 1,1
6 = 1,2
7 = 1,3
8 = 1,4
9 = 2,0
0 = 2,1
 = 2,2
...

so my question is, why eg arr[1,0] or arr[1,1] is empty?

thanks for your help! sno0z3

The problem is caused by the presence of a newline at the end of each line (and a newline is composed of two characters in a Windows text file).
So you can check for these characters before adding to your array, or simply read the line (thus removing the newline) and then loop over the string obtained extracting char by char and adding them to your array

char[,] arr = new char[5, 5];

for (int i = 0; i < 5; i++)
{
   string curLine = sr.ReadLine();
   for (int j = 0; j < curLine.Length; j++)
   {
      arr[i, j] = curLine[j];
      Console.WriteLine(arr[i, j] + " = {0},{1}", i,j);
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM