开发者

Splitting string and assigning split segments to variables

I hjave the following text read from a txt file but would like to assingn each of the three numbers to induvidual variables how can i achive this?

(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

only now the product of XVAL and ZVAL is displayed as 0.123 8.910 and not 0.123 + 8.910 = 9.033

the 9.033 which is what im after


I like string.Split and TryParse:

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

Since this gives a bit repetetive code, the repeating behavior can be encapsulated into a method (might update the answer with that later; need to rush off to the train...).


Provided that your format is consistent, Regular Expressions would be a good approach to take with getting this information. If you enclose sections of a regular expression in brackets, you can later retrieve the value of those sections of the string using the .Groups property on your RegEx result. Here's a simple example:

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)

You'll want to verify that the regular expression is correct (there's lots of sites online where you can play with regular expressions, and also that the matching groups line up properly (you can play with the Groups to figure out what you need.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜