从文本文件转换为2D数组

时间:2019-03-24 11:23:52

标签: c# arrays

我不知道如何制作功能程序,我想将文本文件传输到2D数组中。

谢谢您的回答

这是我的文本文件的内容:

0000000011
0011100000
0000001110
1000011100
1000000000
0000111111
1000001100
1000000000
1000011000
1000001111

代码:

static void Main(string[] args)
{
    int[,] map = new int[10, 10];

    StreamReader reader = new StreamReader(@"Lode.txt");

    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j < 10; j++)
        {
            **WHAT I SHOULD PUT HERE**

        }
    }            
    reader.Close();
}

2 个答案:

答案 0 :(得分:0)

您应该执行以下操作(用我的评论编码):

var map = new int[10, 10];

using (var reader = new StreamReader("Lode.txt"))  // using will call close automatically
{
    for (var i = 0; i < 10; i++)
    {
        var line = reader.ReadLine();  // read one line from file
        for (var j = 0; j < 10; j++)
        {
            map[i, j] = Int32.Parse(line[j].ToString());  // get one symbol from current line and convert it to int
        }
    }
}

答案 1 :(得分:0)

您可以尝试使用一些LINQ,如下所示:

static void Main(string[] args)
{
    string filePath = @"Lode.txt";

    // Read file contents and store it into a local variable
    string fileContents = File.ReadAllText(filePath);

    /* Split by CR-LF in a windows system, 
       then convert it into a list of chars 
       and then finally do a int.Parse on them
    */

    int[][] map = fileContents.Split('\r', '\n')
                 .Select(x => x.ToList())
                 .Select(x => x.Select(y => int.Parse(new string(y, 1))).ToArray())
                 .ToArray();

}