Home > OS >  Splitting string to multiple variables by multiple Characters Vb Net
Splitting string to multiple variables by multiple Characters Vb Net

Time:04-21

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

CodePudding user response:

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

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

separatedStr = iniValue.Split(splitCharsArray)

CodePudding user response:

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.

  • Related