String.Split() - treating consecutive delimiters as one

In case you want to use a regex to achieve your desired result you would need to use Regex.Split() instead:

using System.Text.RegularExpressions;

string[] columns = new Regex(@"\s+", RegexOptions.Compiled).Split(lineOfText);

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.

Tags:

C#

String