高级替换冻结

时间:2016-09-09 16:38:02

标签: vb.net replace spintax

基本上我正在创建一个工具,在查看“file.txt”行时,如果该行包含该单词,则用该行替换文本框内容中的单词。

基本上如果这条线是:披萨芝士土豆,所有包含“披萨”或“奶酪”或“土豆”的单词将被“披萨芝士土豆”取代

这是我到现在为止所拥有的。但它冻结了,我不知道为什么。请帮我。 :)

    Dim PATH As String = "C:\test.txt"

Sub Repl(x As String)
    For Each line As String In File.ReadLines(PATH)
        Dim myList = New List(Of String)(line.Split("|"c))
        For Each item As String In myList
            If x Is item Then
                TextBox1.Text.Replace(x, line)
            End If
        Next
    Next
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    For Each word As String In TextBox1.Text.Split(" "c)
        Repl(word)
    Next
End Sub

提前谢谢!

1 个答案:

答案 0 :(得分:0)

尝试这样做。

Public Sub DoWork()
    Dim lines = IO.File.ReadAllLines(PATH)
    For Each line In lines
        Dim myList = New List(Of String)(line.Split("-"c))
        For Each item In myList
            If TextBox1.Text.Contains(item) Then
                TextBox1.Text = TextBox1.Text.Replace(item, line)
            End If
        Next
    Next
End Sub

您的读者多次读取文件,效率非常低。此代码读取一次,然后我们只需遍历每一行,而无需担心退出条件等。

然而,由于您不会在每行之后暂停,所以它并没有真正做任何有用的事情,因此您只能查看最后一行。

也无需测试文本框是否包含文本,只需执行替换即可只搜索文本一次。

        For Each item In myList
            TextBox1.Text = TextBox1.Text.Replace(item, line)
        Next

--------编辑--------

要解决更换已经替换的单词的问题,您可以尝试使用替换占位符。

        For Each item In myList
            TextBox1.Text = TextBox1.Text.Replace(item, "#")
        Next
        TextBox1.Text = TextBox1.Text.Replace("#", line)

----------编辑2 ------------------

您想尝试逐字逐句构建新字符串,而不是替换文本框中的文本。这样,你替换的单词已经无法转换。

Function ReplaceWord(word As String, lines As String())
    For Each line As String In File.ReadLines(PATH)
        Dim myList = New List(Of String)(line.Split("|"c))
        For Each item As String In myList
            If word = item Then
                Return line
            End If
        Next
    Next
    Return word
End Function

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim result As New System.Text.StringBuilder
    Dim lines = File.ReadLines(PATH)
    For Each word As String In TextBox1.Text
        result.Append(ReplaceWord(word, lines)).Append(" ")
    Next
    Textbox1.Text = result.ToString()
End Sub