简体   繁体   English

循环浏览文本文件中的内容

[英]Loop through contents in the text file

New TechGuy on this site. 本网站上的新TechGuy。 Thought i'd make this resourceful since im getting ready to graduate and want more programming practice. 自从我准备毕业并想要更多编程实践以来,我认为我会花很多时间。 I have a question: 我有个问题:

I tried looping through a text file I created and I wanted to replace each multiple of 3 with the word "changed". 我尝试遍历创建的文本文件,并想用单词“ changed”替换3的每个倍数。 I created a text file and entered numbers 1-15 on each line. 我创建了一个文本文件,并在每行上输入数字1-15。 My code is below but for some reason it would only change the number 3 and 13. I tried using this link as a resource ( Loop through the lines of a text file in VB.NET ) but that wasnt to helpful. 我的代码在下面,但由于某种原因,它只会更改数字3和13。我尝试使用此链接作为资源( 在VB.NET中循环浏览文本文件的行 ),但这并没有帮助。 Anyway here is my code, can someone help with what i'm doing wrong? 无论如何,这是我的代码,有人可以帮我解决我做错的事情吗?

Public Class numbers

  Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load


    Dim OpenFilePrompt As New OpenFileDialog
    openFilePrompt.ShowDialog()
    Dim currentReader As New System.IO.StreamReader(OpenFilePrompt.FileName)
    txtInput.Text = currentReader.ReadToEnd

    Dim a As String

    Dim numbers As New List(Of String)

    a = txtInput.Text
    numbers.Add(a)

    Dim b As Integer

    For i = 0 To numbers.Count Step 3
        b = b + 3

        TextBox2.Text = (numbers.Item(i).Replace(b.ToString, "Changed"))

    Next


  End Sub


End Class 

You are setting numbers (the first item) to a , which is txtInput.Text . 您设置numbers (第一项),以a ,这是txtInput.Text Then you have a one size list which is completely useless! 然后,您有一个完全没有用的尺寸列表!

You should use Mod instead. 您应该改用Mod

Divides two numbers and returns only the remainder. 除以两个数字,仅返回余数。

So just check if Integer Mod 3 equals 0 . 因此,只需检查Integer Mod 3等于0

Also consider using File.ReadAllLines(String) , Val(String) , String.Join(String, String()) and File.WriteAllLines(String, String()) . 还可以考虑使用File.ReadAllLines(String)Val(String)String.Join(String, String())File.WriteAllLines(String, String())

Dim Content() As String = File.ReadAllLines(OpenFilePrompt.FileName)
For Index As Integer = 0 To Content.Length - 1
    Dim Number As Integer = Val(Content(Index))
    If Number Mod 3 = 0 Then
        Content(Index) = "changed"
    End If
Next
txtInput.Text = String.Join(vbCrLf, Content)
File.WriteAllLines(OpenFilePrompt.FileName, Content)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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