2010-11-29 231 views
0

我喜歡從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這是林後

回答

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) 

你要驗證的正則表達式是正確的(有很多網站在網上,你可以使用正則表達式玩,也是匹配的組正常排隊(你可以同組打找出你需要什麼

+0

我設法編寫了以下代碼(請參閱eddit) – alf 2010-11-29 15:28:16

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 

因爲這給了一下的repetetive碼,重複行爲可以被封裝到一個方法(可能稍後更新答案;需要趕往火車......)。