在特定行上读取文本文件时自动添加递增数

时间:2016-12-09 15:35:36

标签: vb.net

当我正在阅读文本文件时,我需要能够自动为特定行添加数字 假设我保存了5行(1个问题和4个回答) 我需要我的程序自动添加问题#“1-2-3-4-5每次它在文本框中的问题行上。 所以它看起来像那样

问题#1< ----我需要什么

答:一个<​​/ P>

答案:B

答案:C

答案:d

问题#2&lt; -----我需要什么

1 个答案:

答案 0 :(得分:0)

以下是您所追求的基础知识。 第一个例子假设您将向以“问题”一词开头的每一行添加一个问题编号

Imports System.IO
    Sub Main()

        Dim sourceFile As String
        Dim newFile As String
        Dim tracker As Integer = 0


        sourceFile = "C:\\temp\\43494_1.txt"
        newFile = "C:\\temp\\43494_1_new.txt"


        Using sw As New StreamWriter(newFile) 'write the new file
            Using sr As New StreamReader(sourceFile) 'read the source file
                Dim currentLine As String = String.Empty
                While (sr.Peek >= 0) 'while there is something to read
                    currentLine = sr.ReadLine()
                    If currentLine.ToLower.StartsWith("question") Then
                        tracker = tracker + 1 'increment the question tracker
                        sw.WriteLine(currentLine & tracker)
                    Else
                        sw.WriteLine(currentLine)
                    End If

                End While
            End Using
        End Using

    End Sub

第二个例子假设对于每个问题,总有4个答案,这意味着每个问题实际上是一个5行的块,并且该片段假定源文件的第1行是第一个问题。

    Imports System.IO
    Sub Main()
        Dim sourceFile As String
        Dim newFile As String
        sourceFile = "C:\\temp\\43494_1.txt"
        newFile = "C:\\temp\\43494_1_new.txt"

        Dim lineTracker As Integer = 0
        Dim questionTracker As Integer = 0

        Using sw As New StreamWriter(newFile) 'write the new file
            Using sr As New StreamReader(sourceFile) 'read the source file
                Dim currentLine As String = String.Empty
                While (sr.Peek >= 0) 'while there is something to read
                    currentLine = sr.ReadLine()

                    'reset the lineTracker if you need to
                    If lineTracker = 5 Then
                        lineTracker = 0
                    End If

                    lineTracker = lineTracker + 1 'increment the lineTracker

                    If lineTracker = 1 Then
                        questionTracker = questionTracker + 1 'increment the question tracker
                        sw.WriteLine(currentLine & questionTracker)
                    Else
                        sw.WriteLine(currentLine)
                    End If
                End While
            End Using
        End Using
    End Sub