在逗号之间获取子串。为什么Mid(字符串,整数,整数)失败?

时间:2013-07-24 19:59:20

标签: vb.net visual-studio substring

我有一个文本框(DropDownList1),其中包含遵循以下格式的46个字符的字符串:

  

(字符串1,字符串,STRING3)

我希望得到没有逗号的字符串值,这样:

a=string1
b=string2
c=string3

所以我使用了以下代码:

Dim a As String
Dim b As String
Dim c As String
Dim x As Integer = InStr(1, DropDownList1.Text, ",", CompareMethod.Text) + 1
Dim y As Integer = InStr(InStr(1, DropDownList1.Text, ",", CompareMethod.Text) + 1, DropDownList1.Text, ",") - 1
Dim z As Integer = Len(DropDownList1.Text)
a = Mid(DropDownList1.Text, 1, InStr(1, DropDownList1.Text, ",", CompareMethod.Text) - 1)
b = Mid(DropDownList1.Text, x, y) _
   'InStr(1, DropDownList1.Text, ",", CompareMethod.Text) + 1, _
   'InStr(InStr(1, DropDownList1.Text, ",", CompareMethod.Text) + 1, DropDownList1.Text, ",") - 1)
c = Mid(DropDownList1.Text, _
    InStr(InStr(1, DropDownList1.Text, ",", CompareMethod.Text) + 1, DropDownList1.Text, ",") + 1, _
    Len(DropDownList1.Text))

然而,当我调试它时:

x = 18(我使用的字符串是正确的)
y = 42(也正确)
z = 46(正确)
a = string1(是的!)
c = string3(是的!)

和b = string2,string3 ----->这里发生了什么?

你能说出我的代码有什么问题吗?我根本就没有得到它

4 个答案:

答案 0 :(得分:3)

对字符串使用Split()函数,将其应用于某个字符串数组变量,然后根据需要将值分配给变量。

答案 1 :(得分:3)

假设x,y和z仅用于调试,它实际上是你关心的a,b和c,并且字符串的重要部分没有逗号或括号:

Dim values = DropDownList1.Text.Replace("(","").Replace(")","").Split(","c)
Dim a as String = values(0)
Dim b As String = values(1)
Dim c As String = values(2)

答案 2 :(得分:1)

如果您实际上使用的是VB.NET,则可以使用Split函数。

Dim text As String = "a,b,c"
Dim parts As String() = text.Split(CChar(","))
Dim a As String = parts(0)
Dim b As String = parts(1)
Dim c As String = parts(2)

答案 3 :(得分:0)

试一试......

Private Sub ParseMyString()
    Dim TargetString() As String = Split("string1,string2,string3", ",")
    Dim Count As Integer = 0
    Dim Result As String
    Const ASC_OFFSET As Integer = 97

    Result = ""
    Do Until Count > UBound(TargetString)
        Result = Result & Chr(ASC_OFFSET + Count) & "=" & TargetString(Count) & vbCrLf
        Count = Count + 1
    Loop
    MsgBox(Result)
End Sub