将文本文件2D数组转换为整数2D数组

时间:2016-06-19 06:16:33

标签: c# arrays text-files

我正在尝试使用来自文本文件(matrix [i,j])的数据。我的代码适用于一维数组,但不适用于二维数组。我尝试使用不同的方法,但总是出错。

 string fileContent = File.ReadAllText(file path);
 string[] integerStrings = fileContent.Split(new char[] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
 integers = new int[integerStrings.Length];
 for (int n = 0; n < integerStrings.Length; n++)
 integers[n] = int.Parse(integerStrings[n]);

我将其修改为

  string fileContent = File.ReadAllText(path);
        string[,] integerStrings = fileContent.Split(new char[,] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
        integers = new int[integerStrings.Length,2];
        for (int n = 0; n < integerStrings.Length; n++)
            for (int j = 0; j <2; n++)
                integers[n,j] = int.Parse(integerStrings[n,j]);

文本文件

0   0   
2   0   
4   0   
6   0   
8   1   
10  1   
12  1   
14  2   
16  3   
18  3   

请注意,我需要的代码应该可以使用行号

进行修复

2 个答案:

答案 0 :(得分:1)

如果你想要2d数组拆分方法只提供1d数组,那么你必须拆分两次......

首先按换行符分隔,然后按空格分割......

string[] rows = fileContent.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

int[,] result = new int[rows.Length,2];

for(int i = 0; i < rows.Length; i++)
{
     var col = rows[i].Split(new char{' ','\t'}, StringSplitOptions.RemoveEmptyEntries);

     result[i,0] = int.Parse(col[0]);
     result[i,1] = int.Parse(col[1]);
}

答案 1 :(得分:1)

从文件中获取行然后拆分每行以获取您的2d数组。这是粗略的初稿。如果需要,您可以测试和重构以改进它。

int[,] matrix = null;
int rowCount = 0;
int colCount = 0;
var lines = File.ReadAllLines(path);
rowCount = lines.Length;
for(int i = 0; i < rowCount; i++) {
    var line = lines[i];
    var tokens = line.Split(new []{' ', '\t'}, StringSplitOptions.RemoveEmptyEntries);        
    if(matrix == null) {
        colCount = tokens.Length;
        matrix = new int[rowCount, colCount];
    }
    for(int j = 0; j < colCount; j++) {
        matrix[i, j] = int.Parse(tokens[j]);
    }
}

这部分用于显示矩阵

int rowLength = matrix.GetLength(0);
int colLength = matrix.Rank;

for (int i = 0; i < rowLength; i++) {
    for (int j = 0; j < colLength; j++) {
        Console.Write(string.Format("{0} ", matrix[i, j]));
    }
    Console.WriteLine();
    Console.WriteLine();
}
Console.ReadLine();