简体   繁体   English

从文本文件到二维数组

[英]from text file into 2D array

I don't have idea how make functional program and I wanna transfer text file into 2D array.我不知道如何制作功能程序,我想将文本文件传输到二维数组中。

Thank you for answers谢谢你的回答

This is content of my text file:这是我的文本文件的内容:

0000000011
0011100000
0000001110
1000011100
1000000000
0000111111
1000001100
1000000000
1000011000
1000001111

Code:代码:

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();
}

You should do following (code with my comments):您应该执行以下操作(带有我的评论的代码):

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
        }
    }
}

You can try with a little LINQ as follows:您可以尝试使用一点 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();

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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