拆分字符串并将拆分段分配给变量

时间:2010-11-29 14:54:27

标签: vb.net variables text-files

我从txt文件中读取了以下文本但是想要将这三个数字中的每一个都分配给各个变量我该如何实现?

(234.134, 105.087, 0.000000)

EDDIT:

    Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim str As String
    Dim XVAL As String
    Dim YVAL As String
    Dim ZVAL As String

    Dim strArr() As String
    Dim count As Integer
    str = "(0.123, 4.467, 8.910)"
    strArr = str.Split(", ")
    For count = 0 To strArr.Length - 3
        XVAL = (strArr(count))
    Next
    For count = 0 To strArr.Length - 2
        YVAL = (strArr(count))
    Next
    For count = 0 To strArr.Length - 1
        ZVAL = (strArr(count))
    Next

    Label1.Text = XVAL + ZVAL
    Label2.Text = YVAL
    Label3.Text = ZVAL

End Sub

现在只有XVAL和ZVAL的乘积显示为0.123 8.910而不是0.123 + 8.910 = 9.033

9.033这就是我之后的

2 个答案:

答案 0 :(得分:1)

我喜欢string.SplitTryParse

string input = "(234.134, 105.087, 0.000000)";
string[] numbers = input.Split(
                       new[] { ',', ')', '(' }, 
                       StringSplitOptions.RemoveEmptyEntries);
double x, y, z;
if (double.TryParse(numbers[0], 
                    NumberStyles.Any, 
                    CultureInfo.InvariantCulture, 
                    out x))
{
    // first string was not a valid number
}

if (double.TryParse(numbers[1], 
                    NumberStyles.Any, 
                    CultureInfo.InvariantCulture, 
                    out y))
{
    // second string was not a valid number
}

// and so on

由于这会给出一些重复的代码,因此可以将重复行为封装到一个方法中(稍后可能会更新答案;需要赶紧去火车......)。

答案 1 :(得分:0)

如果您的格式一致,正则表达式将是获取此信息的好方法。如果将正则表达式的部分括在括号中,则可以稍后使用RegEx结果上的.Groups属性检索字符串的这些部分的值。这是一个简单的例子:

Dim toMatch as String = "(234.134, 105.087, 0.00000)"
Dim regEx as Regex = new Regex("\((\d*(\.\d+)?), (\d*(\.\d+)?), (\d*(\.\d+)?)\)")

Dim match as Match = regEx.Match(toMatch)
Dim var1 as Float = Float.Parse(match.Groups(1).Value)
Dim var2 as Float = Float.Parse(match.Groups(3).Value)
Dim var3 as Float = Float.Parse(match.Groups(5).Value)

你需要验证正则表达式是否正确(网上有很多网站,你可以使用正则表达式,还有匹配的组正确排队(你可以和各组一起玩,找出你的意思)需要。