At the risk of publicising that I’m the last person to know this(!), I recently discovered that String.Split() has an overload that takes a parameter
StringSplitOptions.RemoveEmptyEntries that does exactly what it says, like this:
.cf { font-family: Consolas, Courier New, Courier, Monospace; font-size: 9pt; color: black; background: white; }.cl { margin: 0px; }.cb1 { color: blue; }.cb2 { color: #a31515; }.cb3 { color: #2b91af; }
char[] separator = new char[] { ',' };
string[] result;
string toSplit = "Rick,Dave,,Nick,,,Roger,";
result = toSplit.Split(separator,
StringSplitOptions.RemoveEmptyEntries);
foreach (string s in result)
{
Console.WriteLine("[{0}]", s);
}
This is also very useful for splitting text where extra whitespace should be ignored:
.cf { font-family: Consolas, Courier New, Courier, Monospace; font-size: 9pt; color: black; background: white; }.cl { margin: 0px; }.cb1 { color: blue; }.cb2 { color: #a31515; }.cb3 { color: #2b91af; }
string woods = "The woods are lovely, dark and deep.." +
"But I have promises to keep, " +
"And miles to go before I sleep,, " +
"And miles to go before I sleep.";
char[] whitespace = { ' ', ',', ';', ':', '.', '!', '?' };
string[] words = woods.Split(whitespace,
StringSplitOptions.RemoveEmptyEntries);
foreach (string s in words)
{
Console.WriteLine("[{0}]", s);
}