如何查找缺少哪一行“ {”“}”

时间:2019-01-01 20:32:55

标签: basic

我想制作一个类似Missing Bracket Finder的程序,但是我想让它告诉我哪个行缺少{或},我完全是新手,对不起我的英语不好。

这是我的代码:

Public Class Form1

    Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
        TextBox1.Text = OpenFileDialog1.FileName
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        OpenFileDialog1.ShowDialog()
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        If System.IO.File.Exists(OpenFileDialog1.FileName) Then
            MsgBox("Number '{':" & System.IO.File.ReadAllText(OpenFileDialog1.FileName).Count(Function(x) x = "{") & "    " & "Number '}':" & System.IO.File.ReadAllText(OpenFileDialog1.FileName).Count(Function(x) x = "}"), MsgBoxStyle.OkOnly, "Info")
        Else
            MsgBox(TextBox1.Text & vbNewLine & "File not found." & vbNewLine & "Please verify the correct file name was given.", MsgBoxStyle.Exclamation, "Open")
        End If
    End Sub

End Class

2 个答案:

答案 0 :(得分:0)

对于您要解决的编程问题,我认为最好逐行读取文件。对于您阅读的每一行,您只需搜索“ {”和“}”的索引。如果搜索索引不会产生(-1),则说明您缺少“ {”或“}”。您可以查看下面的示例代码。我没有编写任何错误检查条件,因此您必须自己实现。

Module VBModule
    Sub Main()
        Dim fileName As String = "test.txt"
        Dim fileReader As System.IO.StreamReader
        Dim lineNumber As Integer = 0
        Dim lineContent As String
        fileReader = My.Computer.FileSystem.OpenTextFileReader(fileName)

        while fileReader.Peek() <> -1
            lineNumber = lineNumber + 1 ' <-- Move this to the bottom to start at line 0.
                                        '     Otherwise, it currently start at line 1.
            lineContent = fileReader.readLine()
            if ( lineContent.indexOf("{") = -1 ) then
                Console.WriteLine("Line " + lineNumber.toString() + " missing { ")
            end if
            if ( lineContent.indexOf("}") = -1 ) then
                Console.WriteLine("Line " + lineNumber.toString() + " missing } " )
            end if
        end while
    End Sub
End Module

以下是test.txt文件的内容:

abc {}
buffer{
c}
d

答案 1 :(得分:-1)

是的, 这是一个简单的技巧,很普遍,并在这些程序和调试器中普遍使用。您只需为每种类型的括号设置一个计数器,当其为“ {”时加1,然后在相反的方向上减一。您不会得到的线,但是一旦您得出负值,近似解就可以使用,您应该始终最终得到0,并且永远不会有负值。如果仍然要行,则仅留空白。计算空的空间并计算出大括号,但不建议这样做。