Half-Blood prince - 1 year ago 102
Vb.net Question

Convert numbers in a string to array in visual basic

I am inputing numbers with coma between two numbers,I need to store these number into an array of double elements,with ignoring any other character user has input.But problem is textbox indices and array index are different.And also 2.4 is stored as each seperate elements.
For example i have a string A = "1,2.4,5.4,6,2" . How to convert this to array with element (1),(2.4),(5.4),(6),(2) .

Utilizing the `String.Split()` function and combining that with a `For`-loop should give you the result that you want.

This will also check if it actually is a number or not, to avoid errors:

``````Public Function StringToDoubleArray(ByVal Input As String, ByVal Separators As String()) As Double()
Dim StringArray() As String = Input.Split(Separators, StringSplitOptions.RemoveEmptyEntries) 'Split the string into substrings.
Dim DoubleList As New List(Of Double) 'Declare a list of double values.

For x = 0 To StringArray.Length - 1
If Double.TryParse(StringArray(x), Nothing) = True Then 'Check that the string is parsable into a double.
End If
Next

Return DoubleList.ToArray() 'Convert the list into an array.
End Function
``````

The `Separators As String()` parameter is an array of strings that the function should split your string by. Every time you call it you can initialize a new array with the separators you want (a single separator is fine).

For example:

``````StringToDoubleArray("1,2;3", New String() {",", ";"})
``````

The above will split by commas (`,`) and semicolons (`;`).

``````Dim Values As Double() = StringToDoubleArray(TextBox1.Text, New String() {","}) 'Uses a comma as the separator.