I am splitting a string based on whitespace as follows:
string myStr = "The quick brown fox jumps over the lazy dog";
char[] whitespace = new char[] { ' ', '\t' };
string[] ssizes = myStr.Split(whitespace);
It's irksome to define the char[] array everywhere in my code I want to do this. Is there more efficent way that doesn't require the creation of the character array (which is prone to error if copied in different places)?
Can't you do it inline?
Otherwise, if you do this exact thing often, you could always create constant or something containing that char array.
As others have noted you can according to the documentation also use
null
or an empty array. When you do that it will use whitespace characters automatically.Note that adjacent whitespace will NOT be treated as a single delimiter, even when using
String.Split(null)
. If any of your tokens are separated with multiple spaces or tabs, you'll get empty strings returned in your array.From the documentation:
You can just do:
MSDN has more examples and references:
http://msdn.microsoft.com/en-us/library/b873y76a.aspx
If repeating the same code is the issue, write an extension method on the String class that encapsulates the splitting logic.
Yes, There is need for one more answer here!
All the solutions thus far address the rather limited domain of canonical input, to wit: a single whitespace character between elements (though tip of the hat to @cherno for at least mentioning the problem). But I submit that in all but the most obscure scenarios, splitting all of these should yield identical results:
String.Split
(in any of the flavors shown throughout the other answers here) simply does not work well unless you attach theRemoveEmptyEntries
option with either of these:As the illustration reveals, omitting the option yields four different results (labeled A, B, C, and D) vs. the single result from all four inputs when you use
RemoveEmptyEntries
:Of course, if you don't like using options, just use the regex alternative :-)
If you just call:
or:
then white-space is assumed to be the splitting character. From the
string.Split(char[])
method's documentation page.Always, always, always read the documentation!