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!

3
  • 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. Commented Oct 27, 2011 at 16:37
  • 1
    see msdn.microsoft.com/en-us/library/system.string.split.aspx for all the overloads of string.split() Commented Oct 27, 2011 at 17:03
  • 1
    I'm coming here after investigating String.Split is not removing the split text, only the first letter, 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". Commented Sep 20, 2017 at 22:53

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.