0

I need to split string by multiple characters, and store it to multiple variables. i want to split it by "Comma (,)" and "Semicolon (;)"

I am using This Code:

separatedStr() As String
separatedStr = iniValue.Split(Convert.ToChar(","))

For pos As Integer = 0 To separatedStr.Count - 1
    Select Case pos
       Case 0
            Integer.TryParse(separatedStr(pos), tempPhaseBoardNumber)
       Case 1
            Integer.TryParse(separatedStr(pos), tempChannelNumber)
       Case 2
            Integer.TryParse(separatedStr(pos), tempAdditionalInfo1)
       Case 3
            Integer.TryParse(separatedStr(pos), tempAdditionalInfo2)
       Case Else
 End Select

Next

This code is working in case my string is like this 1,15,20,11 But if in my string Semicolon (;) is coming like 1,15;15,5 then it not working fine. How can i use this code so that it split on basis of both

"Comma" and Simicolon

1
  • 1
    You can simply pass an array of chars to split by to the Split method: String.Split Commented Apr 21, 2022 at 9:50

2 Answers 2

1
Dim splitCharsArray() As Char = {",", ";"}

Just passed this char array to Split Function and it working.

separatedStr = iniValue.Split(splitCharsArray)
Sign up to request clarification or add additional context in comments.

Comments

1

This:

separatedStr = iniValue.Split(Convert.ToChar(","))

should be this:

separatedStr = iniValue.Split(","c)

That's a Char literal. If you want to split on multiple different characters, just pass multiple Char literals:

separatedStr = iniValue.Split(","c, ";"c)

That overload of Split has a parameter of type Char(), i.e. Char array, but it is declared ParamArray. That means that you can pass a single array, or multiple distinct elements without explicitly creating the array. Of course, if you're going to use the same array of delimiters in multiple places, it would be better to create the array explicitly in one place and then use it in multiple places.

Comments

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.