将文本文件的内容存储到char [,]数组中

时间:2017-11-11 06:48:21

标签: c# arrays 2d

我正在尝试获得一个坐标系,调整x和y值将决定输出我的char的位置。例如,如果我的文本文件包含以下内容:

1 2 3

4 5 6

7 8 9

当我输出数组[2,3] =“X”时,我会得到

1 2 3

4 5 6

7 X 9

目前,我的数组只存储txt内容的第一行。我希望它显示文本中的值1到9。  我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace ConsoleApp2Test
{

public class Program

{
    public int xLocation;
    public int yLocation;

    public static void Main()
    {
        int counter = 0;
        string directory = System.IO.Directory.GetParent(System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString()).ToString();
        directory += @"/Maps/Level1.txt";
        char[,] array1 = new char[3, 3];

        for (int i = 0; i < array1.GetLength(0); i++)
        {
            for (int j = 0; j< array1.GetLength(1); j++)
            {
                array1[i, j] = (Char)File.ReadAllBytes(directory)[counter];
                Console.Write(array1[i, j]);
                ++counter;
            }               
        }          
    }

}
}

我做错了吗?

1 个答案:

答案 0 :(得分:1)

好吧,您的文字似乎比文本文件更具特色。您正在迭代3x3 array1的每个元素,但您的文本文件有11个字符(空白也是如此)。

这是一个动态的(但非常天真)approch:

  1. 使用ReadAllText而非ReadAllBytes
  2. 阅读文件内容
  3. Split数组由空白符号
  4. 遍历每个标志并将其放入地图
  5. 来源:

    public static void Main()
    {
        string directory = System.IO.Directory.GetParent(System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString()).ToString();
        directory = Path.Combine(directory, @"/Maps/Level1.txt"); // Better use Path.Combine for combining paths
    
        // It is enough to read the text once and not on every iteration
        string fileContent = File.ReadAllText(directory);
    
        // In your provided sample the blank sign signals a new row in the matrix
        string[] rows = fileContent.Split(' ');
    
        // Assuming that it is a matrix, which must always be the same width per line
        // NullChecks ...
        int rowLength = rows[0].Length;
        int rowCount = rows.Length;
        char[,] map = new char[rowLength, rowCount];
    
        for (int i = 0; i < rowCount; i++)
        {
            for(int j = 0; j < rowLength; j++)
            {
                map[i, j] = rows[i][j];
                Console.Write(map[i, j]);
            }
            // We are done with this row, so jump to the next line
            Console.WriteLine();
        }
    }