I have a comma separated string like this
Dim str as String = "1,5"
Dim num1, num2 As Integer
What I want is I want to separate the string through Comma and store these values to the new integer variables. After separation I want something like this
num1 = 1
num2 = 5
I want to do something like this.
num1, num2 = Convert.ToInt32(str.Split(","))
this is possible in Python but I don't know how to do it here
CodePudding user response:
You can split your string and assign into variables like this:
Private Sub AssignVars()
Dim str As String = "1,5"
Dim num1, num2 As Integer
Dim results() As String
results = str.Split(Convert.ToChar(","))
For pos As Integer = 0 To results.Count - 1
Select Case pos
Case 0
Integer.TryParse(results(pos), num1)
Case 1
Integer.TryParse(results(pos), num2)
Case Else
'error handle?
End Select
Next
End Sub
CodePudding user response:
Another approach
Dim str As String = "b,1,,5,a,,6"
Dim num1, num2 As Integer
Dim results() As Integer
results = (From s In str.Split(","c)
Where Integer.TryParse(s, Nothing)
Select Integer.Parse(s) Take 2).ToArray
If results.Length = 2 Then
num1 = results(0)
num2 = results(1)
Else
'error
End If