8

I'm having some issues using the String.Split method, Example here:

Dim tstString As String = "something here -:- URLhere"
Dim newtstString = tstString.Split(" -:- ")
MessageBox.Show(newtstString(0))
MessageBox.Show(newtstString(1))

The above, in PHP (my native language!) would return something here AND URLhere in the message boxes.

In VB.NET I get:

something here

AND

: (colon)

Does the String.Split only work with standard characters? I can't seem to figure this one out. I'm sure it's something very simple though!

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Chris
  • 512
  • 1
  • 16
  • 33
  • I have got it working by altering the line to: Dim newtstString = Split(tstString, "-:-") Although I am still unsure as to why String.Split wouldn't work properly. – Chris Oct 27 '11 at 16:37
  • 1
    see http://msdn.microsoft.com/en-us/library/system.string.split.aspx for all the overloads of string.split() – Jim Oct 27 '11 at 17:03
  • 1
    I'm coming here after investigating [String.Split is not removing the split text, only the first letter](https://stackoverflow.com/q/46330993/150605), and when I run your code `newTstString` is `{ "something", "here", "-:-", "URLhere" }`, which is what I would expect now that I know that `tstString.Split(" -:- ")` is functionally equivalent to `tstString.Split(" ")`. The output listed in this question is what you would get if you ran `tstString.Split("-")`, although there would be a third element in the resulting array, `" URLhere"`. – Lance U. Matthews Sep 20 '17 at 22:53

1 Answers1

17

This is what you need to do, to prevent the string from being converted to a Char array.

    Dim text As String = "something here -:-  urlhere"
    Dim parts As String() = text.Split(New String() {" -:- "}, StringSplitOptions.None)

This is the System.String member function you need to use in this case

Public Function Split(ByVal separator As String(), ByVal options As StringSplitOptions) As String()
John Alexiou
  • 28,472
  • 11
  • 77
  • 133
  • 1
    It should be noted that it does not convert the string into a `Char` array, rather, it uses the first character of the string and only passes that single character to [this `Split` overload](https://learn.microsoft.com/en-us/dotnet/api/system.string.split?view=netframework-4.8#System_String_Split_System_Char___). This is what happens when you let VB implicitly convert a `String` to a `Char`, and it is another reason to have `Option Strict On`. – GSerg Oct 21 '19 at 21:33