I came across this problem this morning. Here is the code to replicate:
Dim s As String = "C:\program files (x86)\test1\abc.exe"
Console.WriteLine(s.Split("abc.exe")(0))
The result is: c:\progra
and I would expect it to be c:\program files (x86)\test1\
Any ideas what it splits at that point?
You are using the wrong overload. You should be using the one taking a string as a delimiter, that is:
Dim s As String = "C:\program files (x86)\test1\abc.exe"
Console.WriteLine(s.Split(New String() {"abc.exe"}, StringSplitOptions.None)(0))
CLARIFICATION:
The behaviour you observed is one of the typical "drawbacks" of using Option Strict Off
(that's why it is recommendable to always use Option Strict On
if you are not 100% sure of what you are doing): you are using the overload taking a character as separator and VB.NET does not complain because converting automatically string
s into character
s is one of the things which Option Strict On
does. As far as "abc.exe"
does not match any character, VB.NET understands some default value (apparently, a blank space).
Conclusion: when you use Split
with a string (consisting in one character or in 100) as separator, you should use the right overload (, as shown in my code).
Conclusion 2: write always Option Strict On
.
I don't normally do VB so I may be wrong here but my guess would be it's treating your String as a char.
Does VB implicitly cast? If so could it be casting your string into a char
instead? If it were to do so then it would take the value a
which would then split at the a
in program
and explain the behavior your seeing.
Instead use provide the StringSplitOptions
in this alternative Split method call.
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