1

I am not a professional programmer, just FYI.

I am having trouble splitting a string. The resulting array has a length of 3, with the second spot (index 1) being completely empty.

I could manipulate the array to work the way I'd like, but I would rather understand why it is acting this way and code it properly from the beginning.

Dim defaultSetting() As String
Dim curSetting as String = "MENU_ITEM_ON_OPEN;;OPTIONAL_LEAVE"

defaultSetting = curSetting.Split(";;")
MsgBox(defaultSetting.Length) 'this is 3
MsgBox(defaultSetting(0)) 'this is as expected "MENU_ITEM_ON_OPEN"
MsgBox(defaultSetting(1)) 'this is empty and I do not know why
MsgBox(defaultSetting(2)) 'this is "OPTIONAL_LEAVE" and should be stored in defaultSetting(1)

Any help would be appreciated, thank you.

2
  • Take a look at the String.Split method, and in particular the overload with StringSplitOptions. Commented Aug 12, 2020 at 13:45
  • Thanks for your comment dbasnett. After reviewing some stuff I found a solution that works, although, I am not really sure why. Commented Aug 12, 2020 at 14:07

2 Answers 2

2

The problem here is that Option Strict is set to Off.

The overload of Split which is used expects a ParamArray of Char.
Because of this, the string ";;" is "silently" converted to a single char.

You can check this with following code:

Dim x As Char = ";;"
MsgBox(x)

You want to split by a string, which means you have to use another overload:

defaultSetting = curSetting.Split({";;"}, StringSplitOptions.None)
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for the explanation, that makes sense.
No problem. If you think your question is answered, consider to accept an answer (checkmark). So other users can see it's answered.
To avoid issues like this, you should turn Option Strict On in the project properties and also in the IDE options, so it will be On by default for all future projects.
Is ";;" really the delimiter, though, or is it ";" (or if you prefer, ";"c) with an empty entry in the middle?
The reason I was using ";;" is because some of the strings being stored contain one semi colon. It may not have been the best thought out solution, but it was the first thing that came to mind when trying to find something that would never be part of a stored string
0

Thanks to a comment made by dbasnett I was able to find code that worked the way I was expecting, although I am not really sure why if anyone care to explain. But if not, this question has been answered, thanks.

defaultSetting = testString.Split(CType(";;", Char()), StringSplitOptions.RemoveEmptyEntries)

1 Comment

You can use ";"c to denote a character in VB.NET.

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.