[英]Visual Basic Parsing
好的,所以我正在研究一個程序,該程序分析文本框中的輸入並找到一個定界符(例如逗號,空格或使用Enter鍵按下的行),並在每個定界符之前提取每個單詞並將其發布到列表框中。 我仍然不斷出錯。
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim delimiter As String = ""
Dim oldIndex As Integer = 0
Dim newIndex As Integer = 0
Dim length As Integer = 0
Dim tempString As String = ""
Dim tempWord As String = ""
Dim advanceSize As Integer = 0
If RadioButton1.Checked = True Then
delimiter = ","
advanceSize = 1
tempString = TextBox1.Text
length = tempString.Length
Do While oldIndex < length
newIndex = tempString.IndexOf(delimiter)
tempWord = Mid(tempString, oldIndex, newIndex)
tempWord.Trim()
oldIndex = newIndex + advanceSize
ListBox1.Items.Add(tempWord)
Loop
ElseIf RadioButton2.Checked = True Then
delimiter = vbCrLf
advanceSize = 2
tempString = TextBox1.Text
length = tempString.Length
Do While oldIndex < length
newIndex = tempString.IndexOf(delimiter)
newIndex = tempString.IndexOf(delimiter)
tempWord = Mid(tempString, oldIndex, newIndex)
tempWord.Trim()
oldIndex = newIndex + advanceSize
ListBox1.Items.Add(tempWord)
Loop
ElseIf RadioButton3.Checked = True Then
delimiter = " "
advanceSize = 1
tempString = TextBox1.Text
length = tempString.Length
Do While oldIndex < length
newIndex = tempString.IndexOf(delimiter)
newIndex = tempString.IndexOf(delimiter)
tempWord = Mid(tempString, oldIndex, newIndex)
tempWord.Trim()
oldIndex = newIndex + advanceSize
ListBox1.Items.Add(tempWord)
Loop
Else
Exit Sub
在讀取的第一行中,oldindex的值為零。 Mid函數要求第二個參數的數字大於零,因為與string.substring方法不同,它是基於1的,而不是基於0的。 如果將oldindex初始化為1,該錯誤將得到解決。
順便說一句,mid(和.substring)的第三個參數是長度,而不是結束索引。
我可以建議一個可以實現您的問題目標的替代方法嗎? 您可以使用String.Split函數。 有點奇怪,要拆分成一個字符串,您需要使用一個字符串數組(數組中只能有一個,這是我們所需要的),您必須指定一個StringSplitOptions值,但是除此之外易於使用:
Private Sub bnSplitData_Click(sender As Object, e As EventArgs) Handles bnSplitData.Click
Dim txt = tbDataToSplit.Text
Dim delimiter As String() = Nothing
' select case true is an easy way of looking at several options:
Select Case True
Case rbCommas.Checked
delimiter = {","}
Case rbNewLines.Checked
delimiter = {vbCrLf}
Case rbSpaces.Checked
delimiter = {" "}
Case Else ' default value
delimiter = {","}
End Select
Dim parts = txt.Split(delimiter, StringSplitOptions.RemoveEmptyEntries)
' get rid of the old entries
ListBox1.Items.Clear()
' add the new entries all in one go
ListBox1.Items.AddRange(parts)
End Sub
請注意,我是如何給控件(ListBox1除外)賦予有意義的名稱的-它使引用正確的控件變得更加容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.