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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With