sahil sahil - 1 year ago 72
C# Question

String.Split() with default(string[]) as delimiter, how does it work?

In some C# code I saw

default(string[])
is
null
, but the behavior looks like it is splitting based on whitespace:

string[] x = "1 2 3".Split(default(string[]), StringSplitOptions.RemoveEmptyEntries);
string[] y = "1,2, 3".Split(default(string[]), StringSplitOptions.RemoveEmptyEntries);


Here,
x
becomes
string[3] = {"1","2","3"}
,
y
becomes
string[2] = {"1,2,","3"}
.

My input string can be separated using whitespace or comma i.e."1 2 3" OR "1,2, 3". But i want output to be numeric array string i.e. {"1","2","3"}

How can I achieve this?

Answer Source

It makes no sense to use default(string[]) as an argument, because that can (and will by the compiler) be simplified to merely null, which is way more readable.

Then you'll go and read the docs:

If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. White-space characters are defined by the Unicode standard and return true if they are passed to the Char.IsWhiteSpace method.

If you want to split on multiple delimiters, then try searching for that: splitting a string based on multiple char delimiters