Vb 2010如何分割(爆炸)一个字符串

时间:2022-06-17 22:05:00

Based on the code I provided I would like to explode a string into two. The code is working but only if SearchQuery contains two phrases.

基于我提供的代码,我想将一个字符串分成两部分。代码正在运行,但前提是SearchQuery包含两个短语。

Private Sub SearchTxt_PreviewKeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles SearchTxt.PreviewKeyDown
    Dim SearchQuery As String = SearchTxt.Text
    Dim MyString As System.String
    MyString = SearchQuery

    Dim OutPutArray() As System.String
    OutPutArray = Split(MyString, " ", -1)
    ''MsgBox(OutPutArray(0)) - Working

    MsgBox(OutPutArray(1)) ' error - Index was outside the bounds of the array.

end sub

1 个解决方案

#1


An array is always zero based (every type of collection is), so OutPutArray(1) tries to access the second item not the first. If it contains only one you get the exception.

数组始终为零(每种类型的集合都是),因此OutPutArray(1)尝试访问第二个项而不是第一个项。如果只包含一个,则会获得异常。

Instead you want: OutPutArray(0)

相反,你想要:OutPutArray(0)

If you don't know if it contains two, check it:

如果您不知道它是否包含两个,请检查它:

Dim first As String = OutPutArray(0)
Dim second As String = Nothing
If OutPutArray.Length > 1 Then 
    second = OutPutArray(1)
End If

As an aside, i recommend to use .NET methods, so String.Split:

顺便说一句,我建议使用.NET方法,所以String.Split:

Dim OutPutArray As String() = MyString.Split() ' splits by white-spaces, tabs or newlines

or, if you only want to split by spaces:

或者,如果您只想按空格分割:

 Dim OutPutArray As String() = MyString.Split({" "}, StringSplitOptions.None) 

#1


An array is always zero based (every type of collection is), so OutPutArray(1) tries to access the second item not the first. If it contains only one you get the exception.

数组始终为零(每种类型的集合都是),因此OutPutArray(1)尝试访问第二个项而不是第一个项。如果只包含一个,则会获得异常。

Instead you want: OutPutArray(0)

相反,你想要:OutPutArray(0)

If you don't know if it contains two, check it:

如果您不知道它是否包含两个,请检查它:

Dim first As String = OutPutArray(0)
Dim second As String = Nothing
If OutPutArray.Length > 1 Then 
    second = OutPutArray(1)
End If

As an aside, i recommend to use .NET methods, so String.Split:

顺便说一句,我建议使用.NET方法,所以String.Split:

Dim OutPutArray As String() = MyString.Split() ' splits by white-spaces, tabs or newlines

or, if you only want to split by spaces:

或者,如果您只想按空格分割:

 Dim OutPutArray As String() = MyString.Split({" "}, StringSplitOptions.None)