8
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.

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Shaiju T
  • 6,201
  • 20
  • 104
  • 196
  • And why wouldn't you check for the delimiter before splitting? The question title is the obvious answer... – neeKo Aug 28 '18 at 06:01
  • 1
    Because this is the way `string.Split()` works? https://msdn.microsoft.com/de-de/library/b873y76a(v=vs.110).aspx – royalTS Aug 28 '18 at 06:03
  • 2
    "Why the output is Apple ?" Because that is the result most people would expect. Throwing away the only entry just because there is no second or third one is not a standard use case. – oerkelens Aug 28 '18 at 06:03
  • You can split `string` only if it contains your delimiter. – Shai Aug 28 '18 at 06:05

2 Answers2

22

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];
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
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

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44