Difference between using Split with no parameters and RemoveEmptyEntries option
Asked Answered
R

2

11

I'm checking lines in a given text file. Lines may have random whitespace and I'm only interested in checking the number of words in the line and not the whitespace. I do:

string[] arrParts = strLine.Trim().Split();

if (arrParts.Length > 0)
{ 
    ...
}

Now, according to msdn,

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.

The IsWhiteSpace method covers many diverse forms of whitespace including the usuals: ' ' \t and \n

However recently I've seen this format used:

Split(new char[0], StringSplitOptions.RemoveEmptyEntries)

How is this different?

Ruscher answered 10/1, 2014 at 15:17 Comment(0)
F
11

Consider the following string:

"Some  Words"//notice the double space

Using Split() will split on white space and will include 3 items ("Some", "", "Words") because of the double space.

The StringSplitOptions.RemoveEmptyEntries option instructs the function to discount Emtpy entries, so it would result it 2 items ("Some", "Words")

Here is a working example


For completeness, the new char[0] parameter is supplied in order to access the overload that permits specifying StringSplitOptions. In order to use the default delimiter, the separator parameter must be null or of zero-length. However, in this case using null would satisfy multiple overloads so you must specify a valid type (either char[] or string[]). This can be done multiple ways, such as (char[])null or null as char[], or by using a zero-length char array like above.

See here for more information

Floorage answered 10/1, 2014 at 15:22 Comment(0)
W
0

Without using RemoveEmptyEntries you might get empty strings in the result array.

War answered 10/1, 2014 at 15:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.