【问题标题】:How to create a multidimensional array from a .txt-file?如何从 .t​​xt 文件创建多维数组?
【发布时间】:2016-09-20 08:35:33
【问题描述】:

使用ReadAllLines 不会创建可操作的数组,而只会创建“它只是读取文本”。代码如下:

class Program
{
    static void Main(string[] args)
    {
        string[] lines = File.ReadAllLines("read.txt");
        foreach (string s in lines)
        {
            Console.WriteLine(s);
        }
        Console.WriteLine("press any key to close console.");

        if (2 == 2)
        {
            lines[1][2] = 2;
        }
    }
}

错误显示:

属性或索引 'string.this[int]' 不能分配给 -- 它是只读的

是否有一段代码可以识别.txt-file 中的数字和顺序?文本文件如下图所示:

.txt 文件中的每一行都应该是一个字符串。我尝试使用foreachfor-loop 运算符的组合,但我不知道应该写什么。

foreach (string s in lines)
        {
            for (int i = 0; i < 13; i++)
            {
                M[i] = 
            }
        }

上面M是一个多维数组,属性和.txt-file一样。

【问题讨论】:

  • 字符串在 .NET 中是不可变的,一旦创建就无法修改。
  • 你可以String.Split逐行空格,这会给你一个字符串数组,每个字符串都是一个数字。然后,您可以将int.Parse 应用于每个“单元格”,结果将是 int[][]。
  • M[i] = s[i] 不起作用吗?
  • File.ReadAllLines("read.txt").Select(x =&gt; x.Split('\x20').Select(int.Parse).ToArray()).ToArray()

标签: c# arrays multidimensional-array


【解决方案1】:

.NET 中没有内置的方法。不过,您可以做的是从文件行创建一个多维数组,如下所示:

private static string[][] ReadAllLines(string filename)
{
    string[] allFileLines = File.ReadAllLines(filename);

    string[][] arr = new string[allFileLines.Length][];

    for (int rowIndex = 0; rowIndex < allFileLines.Length; rowIndex++)
    {
        // Split by the space character and remove blank entries
        arr[rowIndex] = allFileLines[rowIndex].Split(new [] { ' ' },StringSplitOptions.RemoveEmptyEntries);
    }

    return arr;
}

【讨论】:

    【解决方案2】:

    您可以从文本文件创建多维字符数组

    class Program
    {
        static void Main(string[] args)
        {
            char[][] arr = new char[numberofline][];
    
            string[] lines = File.ReadAllLines("read.txt");
    
            for (int i = 0; i < lines.Length; i++)
            {
                for (int j = 0; j < lines[i].Length; j++)
                {
                    arr[i][j] = lines[i][j];
                }
            }
    
            Console.WriteLine("press any key to close console.");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-27
      • 1970-01-01
      • 2012-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多