繁体   English   中英

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

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

我输入的数字以逗号分隔。 我需要将这些数字存储在双元素数组中,而忽略用户输入的任何其他字符。 但是问题在于TextBox索引和数组索引不同,并且2.4也作为每个单独的元素存储。

例如,我有一个这样的字符串

"1,2.4,5.4,6,2"

如何将其转换为带有元素的数组

(1),(2.4),(5.4),(6),(2)

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

这还将检查它是否实际上是一个数字,以避免错误:

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

Separators As String()参数是一个字符串数组,该函数应使用该字符串拆分字符串。 每次调用它时,都可以使用所需的分隔符初始化一个新数组(单个分隔符就可以了)。

例如:

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

上面将用逗号( , )和分号( ; )分隔。

用于您的目的的示例用法:

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

更新:

在线测试: http//ideone.com/bQASvO

暂无
暂无

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

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