将文本文件添加到列表中,然后添加到二维数组中

本文关键字:添加 然后 二维数组 文本 列表 文件 | 更新日期: 2023-09-27 17:58:44

我有一个文本文件,其中包含以下内容:(没有引号和"空格")

  • ##############
  • #空的空间#
  • #空的空间#
  • #空的空间#
  • #空的空间#
  • ##############

我想把整个文件逐行添加到一个列表中:

FileStream FS = new FileStream(@"FilePath",FileMode.Open);
StreamReader SR = new StreamReader(FS);
List<string> MapLine = new List<string>();
foreach (var s in SR.ReadLine())
{
    MapLine.Add(s.ToString());                   
}
foreach (var x in MapLine)
{
    Console.Write(x);
}

我的问题来了:我想把它添加到二维数组中。我试过了:

string[,] TwoDimentionalArray = new string[100, 100];
for (int i = 0; i < MapLine.Count; i++)
{
    for (int j = 0; j < MapLine.Count; j++)
    {
        TwoDimentionalArray[j, i] = MapLine[j].Split(''n').ToString();
    }
}

我还是C#的新手,所以请提供任何帮助都将不胜感激。

将文本文件添加到列表中,然后添加到二维数组中

您可以尝试以下操作:

        // File.ReadAllLines method serves exactly the purpose you need
        List<string> lines = File.ReadAllLines(@"Data.txt").ToList();
        // lines.Max(line => line.Length) is used to find out the length of the longest line read from the file
        string[,] twoDim = new string[lines.Count, lines.Max(line => line.Length)];
        for(int lineIndex = 0; lineIndex < lines.Count; lineIndex++)
            for(int charIndex = 0; charIndex < lines[lineIndex].Length; charIndex++)
                twoDim[lineIndex,charIndex] = lines[lineIndex][charIndex].ToString();
        for (int lineIndex = 0; lineIndex < lines.Count; lineIndex++)
        {
            for (int charIndex = 0; charIndex < lines[lineIndex].Length; charIndex++)
                Console.Write(twoDim[lineIndex, charIndex]);
            Console.WriteLine();
        }
        Console.ReadKey();

这将把文件内容的每个字符保存到二维数组中自己的位置。为此目的,可能还使用了CCD_ 1。

当前,您正在遍历文件的所有行,对于文件的每一行,您都要再次遍历文件的全部行,以便在'n上拆分它们,这已经通过将它们放入MapLine来完成了。

如果你想要一个行数组的每一个字符,并且再次在一个数组中,它应该大致如下所示:

string[,] TwoDimentionalArray = new string[100, 100];
for (int i = 0; i < MapLine.Count; i++)
{
     for (int j = 0; j < MapLine[i].length(); j++)
     {
          TwoDimentionalArray[i, j] = MapLine[i].SubString(j,j);
     }
}

我这样做没有经过测试,所以它可能有问题。重点是,您需要先遍历每一行,然后遍历该行中的每个字母。从那里,您可以使用SubString

另外,我希望我正确理解了你的问题。

相关文章: