I am inputing numbers separated by commas. I need to store these numbers in an array of double elements, ignoring any other character the user has input. But the problem is that TextBox
indices and array indices are different, and also 2.4 is stored as each separate elements.
For example, I have a string like this
"1,2.4,5.4,6,2"
How can I convert this to an array with elements
(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
Dim TempVal As Double 'Declare a temporary variable which the resulting double will be put in (if the parsing succeeds).
If Double.TryParse(StringArray(x), TempVal) = True Then 'Attempt to parse the string into a double.
DoubleList.Add(TempVal) 'Add the parsed double to the list.
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 ( ;
).
Example usage for your purpose:
Dim Values As Double() = StringToDoubleArray(TextBox1.Text, New String() {","}) 'Uses a comma as the separator.
Update:
Online test: http://ideone.com/bQASvO
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.