Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string from text file to integer array

Tags:

c#

file

integer

I wrote this code in order to open a text file in a C# language Each line in the file contains five digits such as

0    0    2    3     6

0    1    4    4     7

0    2    6    9     9

1    0    8    11    9

1    1    12   15    11

2    2    12   17    15

The distance between the number and the other is one tab The problem is when you execute the program this error appears

input string was not in correct format in Convert.ToInt32(t[j])

code:

string[] st = File.ReadAllLines("C:\\testing\\result.txt");
int[,] tmp = new int[st.Length - 1, 5];
for (int i = 1; i < st.Length; i++)
{

   string[] t = st[i].Split(new char[] { ' ' });
   int cnt = 0;
   for (int k = 0; k < t.Length; k++)
        if (t[k] != "")
           { t[cnt] = t[k]; cnt++; }
        for (int j = 0; j < 5; j++)
                tmp[i - 1, j] = Convert.ToInt32(t[j]);
 }

How can i correct that?

like image 478
zozo Avatar asked Jan 05 '23 00:01

zozo


2 Answers

I suggest changing the collection type from 2d array int[,] into jagged one int[][] and then use Linq:

 using System.Linq;

 ...

 int[][] data = File
   .ReadLines(@"C:\testing\result.txt")
   .Select(line => line
       // Uncomment this if you have empty lines to filter out:
       // .Where(line => !string.IsNullOrWhiteSpace(line)) 
      .Split(new char[] {'\t'}, StringSplitOptions.RemoveEmptyEntries)
      .Select(item => int.Parse(item))
      .ToArray())
   .ToArray();  
like image 121
Dmitry Bychenko Avatar answered Jan 06 '23 13:01

Dmitry Bychenko


split char should be a tab character '\t' instead of single space

like image 37
Bhuban Shrestha Avatar answered Jan 06 '23 13:01

Bhuban Shrestha