Search code examples
c#splitwhitespacedelimiter

How to split multiple spaced numbers in lines -C#


I want to read each of the columns I underlined in red line by line. The column values as you guys can see are separated by a few spaces. For example, from the first row I only want to read "1" then "MANDIT" then "CLIENT" etc. The problem is that spacing between the values is not constant.

enter image description here

Here is my code: (There are obvious syntax issues)

  StreamReader myReader = new StreamReader(Path)
  String line = “ “;
  for (int i =0; i <15; i++)
  {
     line = myReader.readLine();
     string[] delimiters = new string[] { ‘ ’,‘  ’,‘   ’,‘    ’ };
     // Accomodating for different sizes of spaces - is this right?

     int[] columnValues = line.Split(delimiters)
  }

Is “stringt [] columnValues = line.Split(delimteres) valid? I have doubles and ints in the data NOT only strings

Thanks guys


Solution

  • Looking carefully at your image it is clear that you have a file with fixed length columns.
    The best approach should be to have an array of lengths and positions for each column desidered. Then read the line and extract each column using the Substring method.

    For example, supposing you are interested in only 4 columns that start at the positions indicated by the pos array and have a length indicated by the len array

    int pos[] = new int[] {0, 50, 100, 150};
    int len[] = new int[] {3, 40, 20, 15};
    ....
    
    string[] values = new string[4];
    string line;
    while((line = myReader.ReadLine()) != null)
    {
       values[0] = line.Substring(pos[0], len[0]);
       values[1] = line.Substring(pos[1], len[1]);
       values[2] = line.Substring(pos[2], len[2]);
       values[3] = line.Substring(pos[3], len[3]);
    
       .... now convert the values and store or use them ....
    }