如何将字符串切成碎片然后将它们存储在数组中

时间:2011-05-03 14:33:32

标签: vb.net arrays

在我的网站上,我有一个文本框,允许用户输入一组这样的数字:

(118,38,137,15,156,14,157,36,152,49,142,57)

如何将这些数字存储在如下数组中?:

[118    38    137   15    156    14    157    36    152    49    142    57]

3 个答案:

答案 0 :(得分:5)

使用Split方法:

yourString = yourString.Substring(1, yourString.Length - 2) ' Trim parentheses.
Dim result As String() = yourString.Split(","c)

Split方法有几个重载,具体取决于目的。我在这里选择了最简单的,只需要一个Character参数,在本例中为","c,一个逗号。

答案 1 :(得分:1)

您可以使用正则表达式:

Dim str As string = "(118,38,137,15,156,14,157,36,152,49,142,57)"
Dim matches As MatchCollection = New Regex(@"\d+").Matches(str)
Dim ints As Integer() = New Integer(matches.Count - 1) }
Dim i as Integer
For i = 0 To ints.Length - 1
    ints[i] = int.Parse(If(matches.Item(i).Value <> Nothing, _
                           a.Item(i).Value, "").ToString())
Next

答案 2 :(得分:0)

请参阅String.Split

myArray = "118,38,137,15,156,14,157,36,152,49,142,57".Split (",")