Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Split() - treating consecutive delimiters as one

Tags:

string

c#

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! !

like image 826
coergo Avatar asked Aug 16 '11 19:08

coergo


People also ask

What is default delimiter of the split () function?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace.


1 Answers

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.

like image 144
dlev Avatar answered Sep 20 '22 12:09

dlev