-1

I'm trying to split a string like

0 2 5 6 8 13

by using

string[] exampleStringArray = exampleString.Split(null)

However, I don't end up getting the strings

0, 2, 5, 6, 8, 13

in my array but there is one empty string at the index 0. How do I prevent this from happening?

And no, I cannot have a string array at the very beginning with these numbers.

Edit: This question is 10 months old but I revisited it and don't understand why it was marked as a duplicate to this question. My problem was an empty string at the beginning of an array, their problem was about splitting a string with multiple whitespaces between the needed values.

tim-kt
  • 304
  • 5
  • 17
  • Passing null is not sensible, you have to specify the character(s) you want to split on. So probably `' '`. – Hans Passant Mar 04 '18 at 13:40
  • @HansPassant I thought so too but for some reason it works in removing a single whitespace which is not at the start or end. – Rotem Mar 04 '18 at 13:40

2 Answers2

3

Use the SplitStringOptions.RemoveEmptyEntries flag with an overload such as:

" 0 2 5 6 8 13".Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries)

Seems null is a valid option:

If the separator argument is null or contains no characters, the method treats white-space characters as the delimiters. White-space characters are defined by the Unicode standard; they return true if they are passed to the Char.IsWhiteSpace method.

But in order to use with the RemoveEmptyEntries flag you need to explicitly cast the type to char[] or string[] in order to resolve the method overload.

" 0 2 5 6 8 13".Split((char[])null, StringSplitOptions.RemoveEmptyEntries)
Rotem
  • 21,452
  • 6
  • 62
  • 109
1

Why would you split on NULL?

you have to split with Space ' '

here is working example: http://rextester.com/CXCB9931

Good luck.

Einav Hacohen
  • 787
  • 5
  • 14
  • 2
    According to the documentation of String.Split null is a valid option and splits by all whitespaces. – tim-kt Mar 04 '18 at 13:48