首页 > 解决方案 > 如何查找缺少哪一行“{”“}”

问题描述

我想制作一个像 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

标签: basic

解决方案


对于您要解决的编程问题,我认为最好逐行读取文件。对于您阅读的每一行,您只需搜索“{”和“}”的索引。如果搜索索引产生 none(-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

推荐阅读