简体   繁体   中英

Why does string.Split(“ ”) returns elements even when the separator is not present?

In the following:

string input = "123";
char [] separators = " ".ToCharArray();
string [] elements = input.Split(separators);

the elements array is of .Length = 1.

Why is that? String 123 does not contain any spaces.

Straight from the documentation :

If this instance does not contain any of the characters in separator, the returned array consists of a single element that contains this instance.

For your second question:

So there is no situation where .Length will be 0 and elements array will be empty?

Yes there is - if you use the StringSplitOptions.RemoveEmptyEntries option on a string that is empty or contains nothing but delimiters:

string input = "---";
char [] separators = new [] {'-'};
string [] elements = input.Split(separators,StringSplitOptions.RemoveEmptyEntries);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM