根据我提供的代码,我想将一个字符串分成两部分。代码正在运行,但前提是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
答案 0 :(得分:2)
数组始终为零(每种类型的集合都是),因此OutPutArray(1)
尝试访问第二项而不是第一项。如果它只包含一个则会得到例外。
相反,您需要:OutPutArray(0)
如果您不知道它是否包含两个,请检查它:
Dim first As String = OutPutArray(0)
Dim second As String = Nothing
If OutPutArray.Length > 1 Then
second = OutPutArray(1)
End If
另外,我建议使用.NET方法,所以String.Split
:
Dim OutPutArray As String() = MyString.Split() ' splits by white-spaces, tabs or newlines
或者,如果您只想按空格分割:
Dim OutPutArray As String() = MyString.Split({" "}, StringSplitOptions.None)