简体   繁体   English

使用 vb.net 替换记事本文本的制表符分隔列

[英]Use vb.net to replace a tab delimited column of notepad text

i want check a specific column in notepad and replace all of them to zero , i have the following code我想检查记事本中的特定列并将它们全部替换为零,我有以下代码

Dim vtext As String
Dim sum As Integer
Dim vstring(-1) As String
Dim p1 As String() = {vbTab}
Dim vData As String = ""

Using sr As New StreamReader("C:\Users\310238479\Desktop" + "\" + database(i) + ".txt")
    While sr.Peek <> -1
        lines.Add(sr.ReadLine)
    End While
End Using
For Each line As String In lines
    vstring = line.Split(p1, StringSplitOptions.RemoveEmptyEntries)
    If (vstring.Length = 11) Then
        If (vstring(10) <> "0") Then
            vstring(10) = "0"
        End If
    End If
Next
Using sw As New StreamWriter("C:\Users\310238479\Desktop" + "\" + database(i) + ".txt")
    For Each line As String In lines
        sw.WriteLine(line)
    Next
End Using

It is suppose to be working but somehow i cant get it to work , i guarantee the extension has no problem .它应该可以工作,但不知何故我无法让它工作,我保证扩展没有问题。 Please give me some advise.请给我一些建议。

Firstly, this has nothing to do with Notepad.首先,这与记事本无关。 Notepad is simply a text file editor.记事本只是一个文本文件编辑器。 There are numerous such applications around.周围有许多这样的应用程序。 A text file is a text file.文本文件是一个文本文件。

Secondly, instead of using loops to read and write lines to a file, just use File.ReadAllLines and File.WriteAllLines to do each in a single line of code.其次,不要使用循环来读取和写入文件的行,只需使用File.ReadAllLinesFile.WriteAllLines在一行代码中完成每一个。

As for the issue, your problem lies here:至于问题,你的问题在于:

For Each line As String In lines
    vstring = line.Split(p1, StringSplitOptions.RemoveEmptyEntries)
    If (vstring.Length = 11) Then
        If (vstring(10) <> "0") Then
            vstring(10) = "0"
        End If
    End If
Next

You loop through what is presumably a List(Of String) and, for each item, you split it into a String array and then possibly change one element of that array.您遍历可能是List(Of String) ,对于每个项目,您将其拆分为一个String数组,然后可能更改该数组的一个元素。 That's all well and good but you then simply discard that array and make no change to your List(Of String) that you later write back to the file.这一切都很好,但是您只需丢弃该数组,并且不对稍后写回文件的List(Of String)进行任何更改。 If you want different text written back to the file then you have to actually change the text you write back to the file.如果您希望将不同的文本写回文件,则必须实际更改写回文件的文本。 That would mean replacing the original line with the concatenated contents of the modified array, eg这意味着用修改后的数组的连接内容替换原始行,例如

For i = 0 To lines.Count - 1
    vstring = lines(i).Split(p1, StringSplitOptions.RemoveEmptyEntries)

    If (vstring.Length = 11) AndAlso (vstring(10) <> "0") Then
        vstring(10) = "0"
        lines(i) = String.Join(ControlChars.Tab, vstring)
    End If
Next

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

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