0

I have a string in the form of myText = "1000 - abc 123 xyz"

When I do myText.split(" - ")(0) I get the value 1000, but myText.split(" - ")(1) I get the value "-", and myText.split(" - ")(2) = "abc"

If I remove the spaces so myText = "1000-abc 123 xyz", myText.split("-")(1) = "abc 123 xyz" as required.

Thought the split character was not included in the array, and why are the spaces influencing the outcome when the are part of the split value.

djv
  • 15,168
  • 7
  • 48
  • 72
Frank Nicklin
  • 105
  • 10
  • 5
    You cannot split like this: `myText.Split(" - ")`. There's no overload of `string.Split()` that accepts these arguments. You have use an array of strings: `myText.Split({" - "}, StringSplitOptions.RemoveEmptyEntries)`. It will return an array of 2 elements, which will not include the separator, of course. – Jimi Oct 30 '19 at 13:43
  • 3
    Option Strict Off doing its usual evil deeds, you are getting the String.Split(Char()) overload. So it will split on spaces as well. With Option Strict On at the top of the source file you'll get a decent compile error message. – Hans Passant Oct 30 '19 at 14:05
  • 1
    Thanks for your help both. Understand now. – Frank Nicklin Oct 30 '19 at 14:42
  • Possible duplicate of [Split a string by another string in C#](https://stackoverflow.com/questions/2245442/split-a-string-by-another-string-in-c-sharp) – Andrew Morton Oct 30 '19 at 14:50

1 Answers1

0

You cannot split like this: myText.Split(" - "). There's no overload of string.Split() that accepts these arguments. You have use an array of strings: myText.Split({" - "}, StringSplitOptions.RemoveEmptyEntries). It will return an array of 2 elements, which will not include the separator, of course.

Answered by Jimi in a comment.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Frank Nicklin
  • 105
  • 10