Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String split with two single quotes

I have a bare string where each word is separated by a comma between two single quotes.

Dim str As String = "a','b','c','d','e"

I want to split the string using ',' so that I have an array as follows:

["a", "b", "c", "d", "e"]

My code is as follows:

str.Split("','")

The array that is returned is ["a", ",", "b", ",", "c", ",", "d", ",", "e"].

I didn't expect this behaviour and am looking for an explanation of how the string is being split.

like image 649
h-rai Avatar asked Aug 26 '26 10:08

h-rai


1 Answers

The reason for the unexpected result is the fact that you are passing a String as the argument to Split.

There is no such overload of Split that accepts a String so because you have Option Strict off, the compiler uses the Split(Char) overload, taking only the first character in the string. So in your case

String.Split("','")

is the same as

String.Split("'")

You want to switch Option Strict On, then your code will not compile (this is a good thing because it avoids mistakes like this).

To achieve what you want, you have to pass an array of strings into the method (in this case an array containing just one string):

    Dim input As String = "a','b','c','d','e"
    Dim splitChars() As String = {"','"}
    Dim output As String() = input.Split(splitChars, StringSplitOptions.None)
like image 152
Matt Wilko Avatar answered Aug 29 '26 07:08

Matt Wilko