【发布时间】:2013-11-24 08:21:31
【问题描述】:
因此,这是我已经编写的代码:
Dim MyFile As String = "Path"
Dim str_new As String
Dim str_old As String = File.ReadAllText(MyFile)
Dim sr As New StreamReader(MyFile)
Dim strLines As String() = Strings.Split(sr.ReadToEnd, Environment.NewLine)
Dim Character As Integer = 5 'Line 1 always has 5 characters
For i = 2 To strLines.Length
Dim PreviousLine As String = sr.ReadLine(i - 1)
Dim CurrentLine As String = sr.ReadLine(i)
If CurrentLine.Contains(TextBox1.Text / 100) Then
If PreviousLine.Contains("divide") Then
Exit For
End If
End If
Character = Character + CurrentLine.Length
Next
sr.Close()
str_new = Replace(str_old, (TextBox1.Text / 100), (TextBox3.Text / 100), Character, 1)
Dim objWriter3 As New System.IO.StreamWriter(MyFile, False)
objWriter3.Write(str_new)
objWriter3.Flush()
objWriter3.Close()
我正在尝试找出一种方法将长代码文件分成几行,然后检查每一行是否有某些字符串。如果当前行包含字符串,那么我将对上面和/或下面的行进行额外检查,以确保这是字符串的正确实例。最后,我想用不同的字符串替换字符串的那个实例。
一个例子:文本文件
class
...
0.3
divide <-- Previous Line
0.3 <-- TextBox1.Text is 30
.5
end
- 我希望代码超过 0.3 的第一个实例
- 找到第二个实例
- 检查上一行是否有除法
- 退出循环
- 将 0.3 的第二个实例替换为某个值
我已经对此进行了一段时间的研究,我们将不胜感激任何帮助! ~马特
修订:代码
Dim MyFile As String = "Path"
Dim NewFile As String = "Temporary Path"
Dim PreviousLine As String = ""
Dim CurrentLine As String = ""
Using sr As StreamReader = New StreamReader(MyFile)
Using sw As StreamWriter = New StreamWriter(NewFile)
CurrentLine = sr.ReadLine
Do While (Not CurrentLine Is Nothing)
Dim LinetoWrite = CurrentLine
If CurrentLine.Contains(TextBox1.Text) Then
If PreviousLine.Contains("divide") Then
LinetoWrite = Replace(CurrentLine, TextBox1.Text, TextBox3.Text)
End If
End If
sw.WriteLine(LinetoWrite)
PreviousLine = CurrentLine
CurrentLine = sr.ReadLine
Loop
End Using
End Using
My.Computer.FileSystem.CopyFile(NewFile, MyFile, True)
【问题讨论】:
-
首先使用变量,而不是文本框。
TextBox1.Text / 100很糟糕; TB 包含文本而不是数字。由于您正在使用结果进行比较,因此您应该格式化结果以便它可以匹配。此外,只使用 NotePad++ 可能会更快。 -
什么版本的.Net?
-
Plutonix ~ 我正在编写一个应用程序,它需要用户输入当前值是什么以及后一个值是什么。我有错误处理以确保字符串只有数字。
标签: vb.net string str-replace