what should be returned for string.Split(“;”) if s

2020-07-03 03:53发布

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.

标签: c# .net
5条回答
何必那么认真
2楼-- · 2020-07-03 04:30

From your code, a isn't null, it's String.Empty. So when you split an empty length string by a semicolon, there's 1 item. 1 - 1 is less than 1

查看更多
太酷不给撩
3楼-- · 2020-07-03 04:35

The code splits the string into components separated with ';' - the result of this operation is the array of strings. If there are less than 2 components the condition is true.

查看更多
We Are One
4楼-- · 2020-07-03 04:38

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.

查看更多
啃猪蹄的小仙女
5楼-- · 2020-07-03 04:45

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.

查看更多
【Aperson】
6楼-- · 2020-07-03 04:53

An empty string is NOT the same as a null string. Strings, being reference types will always contain "" if empty. Null is not at all the same thing, thus, if you have an empty string, it will have a length of 0 and your if statement will be valid.

查看更多
登录 后发表回答