Forum guidelines
  • Home
  • »
  • C# Language
  • »
  • How to read a txt file into a two-dimensional array
AuthorQuestion
How to read a txt file into a two-dimensional array
Posted on: 16 Nov 2010

Hello everyone,
I have a txt file with the following data:
 

line1
line2
line3
 
col1 col2 col3 col4
1 3 12 63
83 10 19 14
21 34 87 54 

I'd like to read that file, remove the header, remove col1 ......col4.
So, at the end I'd like to have the following data in a two-dimensional array so that I can manipulate (copy, sort...) them:
 
1 3 12 63
83 10 19 14
21 34 87 54 

I've found on this and other forums how to read the txt, but no solutions how to remove all these unwanted lines.
I'm reading the file so:
 
string
[] lines = System.IO.File.ReadAllLines(@"E:\Task\myfile.txt");

Thanks for your help
Kabanga
 

AuthorReply
Re: How to read a txt file into a two-dimensional array
Posted on: 16 Nov 2010  
You can split the lines using Split() method

and discard the lines containing alphabets

Again you can split based on space and get the values

         private void Form1_Load(object sender, EventArgs e)
{
string text = new StreamReader("YourFile.txt").ReadToEnd();
int[,] result = CreateArray(text);
}

private int[,] CreateArray(string data)
{
int[,] array = new int[10, 10];
int i = 0, j = 0;

foreach (string line in data.Split(new string[1] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
{
if ((IsNumeric(line) && (line.Trim().Length > 0))) // If valid numeric line and not empty line
{
j = 0;
foreach (string number in line.Split(' '))
if (!string.IsNullOrEmpty(number))
array[i, j++] = int.Parse(number);

i++;
}
}

return array;
}

private bool IsNumeric(string line)
{
foreach(char c in line)
if (!"0123456789 ".Contains(c))
return false;

return true;
}


Architect | Microsoft MVP | MindCracker MVP | BS | MBA | www.jeanpaulva.com
Zoran Horvat
  • 0
  • 0
accepted
Re: How to read a txt file into a two-dimensional array
Posted on: 16 Nov 2010   Accepted Answer
You can use String.Split method with options set to RemoveEmptyEntries, which would split each line into separate items. Then fill jagged array with data obtained in that way.

Here is the code which does that - type lines and finish with a line consisting of single dash (-):
class Program
{

    static void Main(string[] args)
    {
        List list = new List();

        while (true)
        {
            string line = Console.ReadLine();
            if (line == "-")
                break;
            else list.Add(line);
        }

        string[] lines = list.ToArray();
        string[][] cells = new string[lines.Length][];

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

        Console.WriteLine("------------------------------------");
        for (int i = 0; i < cells.Length; i++)
        {
            for (int j = 0; j < cells[i].Length; j++)
                Console.Write("[{0}] ", cells[i][j]);
            Console.WriteLine();
        }
        Console.WriteLine("------------------------------------");

    }
}

Input:
line1
line2
line3

col1 col2 col3 col4
1 3 12 63
83 10 19 14
21 34 87 54
-

Output:
------------------------------------
[line1]
[line2]
[line3]

[col1] [col2] [col3] [col4]
[1] [3] [12] [63]
[83] [10] [19] [14]
[21] [34] [87] [54]
------------------------------------

You can skip headers printing by starting the printout loop from specified index (e.g. 1 instead of 0).

Re: How to read a txt file into a two-dimensional array
Posted on: 17 Nov 2010  
Assuming that the header line "col1 col2 col3 col4" will always be the same, I would read the lines of the file (or loop through the lines string[]) until the line "col1 col2 col3 col4" is found. Then the remainding lines should have the data you need. Then use String.Split to get the data within each record.
Thinking is a feeling; pleasant for some and unpleasant for others.
Jo
  • 0
  • 0
Re: How to read a txt file into a two-dimensional array
Posted on: 17 Nov 2010  

Thanks all for your help !
Using the method of Zoran I could read the data into a 2d array.

Sam, I like your idea. Combining both Zoran's and your idea I'd get exactly what I want.
What I'm doing now is manually  counting the lines till the beginning of numeric data.
With that method, if the number of lines changes, I must manually change the code to adapt to the new situation.

Before the beginning of numeric data in the txt file there is always the string  " End Comments".
I'm wondering if there is any function like "ScanLine( path, stringToFind)" that I'll use for detecting the string " End Comments".
Best regards

 
 

SPONSORED BY

Custom Software Development
MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.