Mohanad Al Nuaimi
Mohanad Al Nuaimi

Reputation: 49

convert Text file 2D array to integer 2D array

I am trying to use data from text file (matrix [i, j]). I have code works with one dimension array but doesn't work with two dimension array. I tried to use different method but I always get an error.

 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]);

I modify it to this

  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]);

the text file

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

Note the code I need should be fixable with rows number

Upvotes: 2

Views: 144

Answers (2)

Nkosi
Nkosi

Reputation: 246998

get the lines from the file then split each line to get your 2d array. Here is a rough first draft. You can test and refactor to improve on it if needed.

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]);
    }
}

this part is for display the matrix

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

Upvotes: 1

M.kazem Akhgary
M.kazem Akhgary

Reputation: 19149

If you want 2d array split method just gives 1d array so you have to split twice...

First split by line breaks then by spaces...

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]);
}

Upvotes: 1

Related Questions