在文件中保存数字到2D数组

本文关键字:2D 数组 数字 保存 文件 | 更新日期: 2023-09-27 18:10:24

我的文件中有一些数字:

22 33 44 55
11 45 23 14
54 65 87 98

,我想把它们保存在一个二维数组中,比如:

x[0][1]==33

我该怎么做??

编辑:

我写了一些部分,我在代码中加了注释:

StreamReader sr = new StreamReader(@"C:'Users'arash'Desktop'1.txt");
        string[] strr;
        List<List<int>> table = new List<List<int>>();
        List<int> row = new List<int>();
        string str;
        while ((str = sr.ReadLine()) != null)
        {
            strr = str.Split(' ');//here how should i save split output in two dimension array??
             }

TIA

在文件中保存数字到2D数组

可以这样做:

StreamReader sr = new StreamReader(@"C:'Users'arash'Desktop'1.txt");
List<int[]> table = new List<int[]>();
string line;
string[] split;
int[] row;
while ((line = sr.ReadLine()) != null) {
    split = line.Split(' ');
    row = new int[split.Count];
    for (int x = 0; x < split.Count; x++) {
        row[x] = Convert.ToInt32(split[x]);
    }
    table.Add(row);
}
然后可以这样访问

表:

table[y][x]

使用嵌套循环可以很容易地创建多维数组。

嵌套两个循环,外部循环遍历输入中的行,内部循环遍历一行中的数字。

或者你可以Linq

var myArray = File.ReadAllLines(@"C:'Users'arash'Desktop'1.txt")
    .Where(s=> !string.IsNullOrWhiteSpace(s))
    .Select(l => l.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries)
        .Select(n => Convert.ToInt32(n)).ToArray()).ToArray();

myArray[0][1]得到33