Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between using Split with no parameters and RemoveEmptyEntries option

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?

like image 275
seebiscuit Avatar asked Jan 10 '14 15:01

seebiscuit


People also ask

What does split () return if the string has no match Java?

split() will return an array.

How split a string after a specific character in C#?

Split(Char[], Int32, StringSplitOptions) Method This method is used to splits a string into a maximum number of substrings based on the characters in an array. Syntax: public String[] Split(char[] separator, int count, StringSplitOptions options);

What is split () method?

Definition and Usage. The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


1 Answers

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

like image 62
musefan Avatar answered Sep 21 '22 20:09

musefan