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?
split() will return an array.
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);
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With