If string is empty or null,
Shouldn't string.split(";") should throw an error ?
for me I am trying this code and goes through it without any error,
string a = string.empty;
if (a.Split(';').Length - 1 < 1)
Can anyone tell me why it not throws an error and why if statement is true.
If the delimiter is an empty string, the split() method will return an array of elements, one element for each character of string. If you specify an empty string for string, the split() method will return an empty string and not an array of strings.
Using split() When the string is empty and no separator is specified, split() returns an array containing one empty string, rather than an empty array. If the string and separator are both empty strings, an empty array is returned.
An empty string has a Length of 0. The following example creates an empty string and displays its value and its length. String^ s = ""; Console::WriteLine("The length of '{0}' is {1}.", s, s->Length); // The example displays the following output: // The length of '' is 0.
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.
If the string is null, .Split()
will (obviously) throw a NullReferenceException
, like any other instance method.
If the string is empty, .Split()
will return an array of a single empty string (unless you pass StringSplitOptions.RemoveEmptyEntries
).
This is a corner case of its more general (and less unexpected) behavior; if the delimiter does not appear anywhere in the source string, it will return an array containing the entire source string.
It should behave as documented:
If this instance does not contain any of the characters in
separator
, the returned array consists of a single element that contains this instance.
An empty string clear does not contain any of the characters in separator
, hence an array is returned consisting of a single element referring to an empty string.
Of course, if you call Split
on a null reference, you'll get a NullReferenceException
. It's important to differentiate between a reference to an empty string and a null reference.
If you want the method to return an empty array, use StringSplitOptions.RemoveEmptyEntries
. If you want the result to be an error, you should check for this yourself and throw whatever exception you want.
It's important not to guess at behaviour when using an API though: if you're in any doubt at all, consult the documentation.
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