【问题标题】:Adding a text file into a list and then into a Two Dimensional array将文本文件添加到列表中,然后添加到二维数组中
【发布时间】:2013-01-26 14:59:36
【问题描述】:

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

  • ##############
  • #空白空间#
  • #空白空间#
  • #空白空间#
  • #空白空间#
  • ##############

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

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# 的新手,所以如果有任何帮助,我们将不胜感激。

【问题讨论】:

  • 你到底想得到什么?似乎您的代码迭代次数太多了。贴一些你想看到的结果的例子。
  • 为什么需要维度?您可以将每一行用作字符串并将其全部包含在一个列表中吗?
  • 大家好,我只想在二维数组中显示文本文件的数据并显示数组
  • 您尝试将List&lt;string&gt; 添加到string[,] 中? string[,]中的元素应该是什么?

标签: c# list for-loop multidimensional-array


【解决方案1】:

你可以试试这个:

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

这会将文件内容的每个字符保存到它自己在二维数组中的位置。为此,可能还使用了char[,]

【讨论】:

  • 轰!!!!!!!我的天啊,非常感谢你完美的工作!!!!!!!我太棒了,非常感谢!!!!!!! :)
  • 太好了,很高兴为您提供帮助:) 如果您认为此答案最有帮助,您可以将其标记为正确。
【解决方案2】:

目前,您正在浏览文件的所有行,并且对于文件的每一行,您再次浏览文件的所有行,将它们拆分为\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.

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

【讨论】:

  • for 循环可以工作,但它不会向数组中添加任何内容。 (对不起,我对 C# 还是很陌生):(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-22
  • 1970-01-01
  • 1970-01-01
  • 2012-10-05
  • 1970-01-01
  • 2021-08-06
相关资源
最近更新 更多