Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unusual behaviour with String.Split

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?

like image 262
user3329538 Avatar asked Mar 04 '14 16:03

user3329538


Video Answer


2 Answers

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 strings into characters 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.

like image 147
varocarbas Avatar answered Sep 21 '22 01:09

varocarbas


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.

like image 20
Ian Avatar answered Sep 25 '22 01:09

Ian