I am trying to parse a set of "fixed width" data files, I use that in quotes because the width is different per data file. However, the fields are separated by X number of spaces so I thought to just read in the line, and then do line.Split(' ')
However, this does not work for consecutive spaces! !
The split() method splits a string into a list. You can specify the separator, default separator is any whitespace.
You have a couple options.
The first is to use the string.Split()
overload that accepts a StringSplitOptions
parameter and pass in StringSplitOptions.RemoveEmptyEntries
:
string[] columns = lineOfText.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);
That way, if you have multiple spaces in a row, the empty entries that are generated will be discarded.
The second option is to use a regular expression to do your parsing. This probably isn't necessary in your case, but could come in handy if the format becomes more complicated, or you expect it to change slightly over time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With