拆分字符串并将其放在文本框中

时间:2017-03-13 17:40:05

标签: vb.net

如何将字符串“V237P023F50.5”拆分为不同的文本框。

我正在尝试这段代码:

Dim input As String = "V237P023F50.5"
TextBox1.Text = input

Dim parts As String() = input.Split(New String() {"V"}, StringSplitOptions.RemoveEmptyEntries)
Dim parts1 As String() = input.Split(New String() {"V", "P"}, StringSplitOptions.RemoveEmptyEntries)
Dim parts2 As String() = input.Split(New String() {"V", "P", "F"}, StringSplitOptions.RemoveEmptyEntries)

For i As Integer = 0 To parts.Length - 1
    If i > 0 OrElse input.StartsWith("V") = True Then
        parts(i) = "" & parts(i)
        TextBox2.Text = parts(i)
    End If
Next

For i As Integer = 0 To parts1.Length - 1
    If i > 0 OrElse input.StartsWith("P") = True Then
        parts1(i) = "" & parts1(i)
        TextBox4.Text = parts1(i)
    End If
Next

For i As Integer = 0 To parts2.Length - 1
    If i > 0 OrElse input.StartsWith("F") = True Then
        parts2(i) = "" & parts2(i)
        TextBox5.Text = parts2(i)
    End If
Next

预期输出

V237  
P023   
F50.5  

请帮帮我。

1 个答案:

答案 0 :(得分:1)

如果这是固定长度,请使用Substring()

Dim oldstring As String = "V237P023F50.5"
TextBox2.Text = oldstring.Substring(0, 4)
TextBox4.Text = oldstring.Substring(4, 4)
TextBox5.Text = oldstring.Substring(8)

如果字母字符相同,那么您可以将IndexOf()与子字符串一起使用。

Dim oldstring As String = "V237P023F50.5"
TextBox2.Text = oldstring.Substring(oldstring.IndexOf("V" ), (oldstring.IndexOf("P") - oldstring.IndexOf("V")))
TextBox4.Text = oldstring.Substring(oldstring.IndexOf("P" ), (oldstring.IndexOf("F") - oldstring.IndexOf("P")))
TextBox5.Text = oldstring.Substring(oldstring.IndexOf("F" ))