繁体   English   中英

Visual Basic解析

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM