Sunday, November 02, 2008

 

String.Split(): Skip Empty Entries

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:

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:

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);
}


    

Powered by Blogger