Visual Basic解析

时间:2015-02-19 20:56:25

标签: visual-studio-2010 parsing textbox listbox

好的,我正在开发一个解析文本框中输入的程序,并找到一个分隔符,例如逗号,空格或使用回车键按下的行,并在每个分隔符之前提取每个单词并将其发布到列表框。我不断收到错误。

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

2 个答案:

答案 0 :(得分:1)

在第一行读取中,oldindex的值为零。对于第二个参数,Mid函数需要大于零的数字,因为与string.substring方法不同,它是基于一个而不是从零开始。如果将oldindex初始化为1,则会解决该错误。

顺便提一下,mid(和.substring)的第三个参数是length,而不是结束索引。

答案 1 :(得分:1)

我可以建议一个可以实现问题目标的替代方案吗?您可以使用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除外)提供有意义的名称 - 它更容易引用正确的名称。