c# split string only if delimiter found

Viewed 11074
string search = "Apple : 100";

string[] result = search .Split(':');

Works fine with below output:

result[0] ==> Apple
result[1] ==> 100

But for this:

string search  = "Apple";    
string[] result = search .Split(':');

Outputs:

result[0] ==> Apple

Why the output is Apple ? I Just want empty array if the delimiter is missing in the search string.

Any help would be appreciated.

2 Answers

The way String.Split works is by returning an array with the split segments. If the delimiter is not present then there is only one segment - the entire string. From documentation (under Return value details):

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

To do what you want you can do:

var result = search.Contains(':') ? search.Split(':') : new string[0];

If string does not contains character which used as a delimiter, then it returns an array containing entire string as a array element. In your case, string Apple, does not contains delimiter. that is the reason, array contains entire string i.e. Apple as a zeroth element

Reference: MSDN Spit() function

Related