简体   繁体   English

在Visual Basic中将字符串中的数字转换为数组

[英]Convert numbers in a string to array in visual basic

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. 但是问题在于TextBox索引和数组索引不同,并且2.4也作为每个单独的元素存储。

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. 利用String.Split()函数,并将其与For -loop结合使用,可以为您提供所需的结果。

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. Separators As String()参数是一个字符串数组,该函数应使用该字符串拆分字符串。 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 在线测试: http//ideone.com/bQASvO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM