【问题标题】:Comparing words in two textbox to find difference?比较两个文本框中的单词以发现差异?
【发布时间】:2017-01-06 20:42:26
【问题描述】:

我有 2 个文本框。

我想比较Textbox1和Textbox2的所有单词

假设 Textbox1 中的第二个单词是“me”,而 Textbox 2 中的第二个单词是“him”,它将突出显示 Textbox 2 上的单词“him”和 Textbox1 上的“me”。

例子:

方框 1 = 我是一个男孩

框 2 = 我是一个女孩

方框1 = 是一个男孩

框 2 =是一个女孩

但现在我在比较单词时遇到了问题。我尝试按数组索引进行比较,但它只会显示在 Textbox1 中找不到的单词!

    Dim txt1(TextBox1.Text.Split(" ").Length) As String
    Dim txt2(TextBox2.Text.Split(" ").Length) As String
    txt1 = TextBox1.Text.Split(" ")
    txt2 = TextBox2.Text.Split(" ")
    Dim diff1 As String = "" 'Differences between 1 and 2
    Dim diff2 As String = "" 'Differences between 2 and 1

    For Each diff As String In txt1
        If Array.IndexOf(txt2, diff.ToString) = -1 Then
            diff1 += diff.ToString & " "
        End If
    Next
    For Each diff As String In txt2
        If Array.IndexOf(txt1, diff.ToString) = -1 Then
            diff2 += diff.ToString & " "
        End If
    Next

我也遇到了无法突出显示文本的问题

【问题讨论】:

  • 你的代码对我有用,检查它(和数组值)逐步执行
  • 如果你想要一些粗体字(但不是全部),使用 RichTextBox 控件而不是 TextBox。
  • @Blackwood 我的网络项目只有工具箱中的文本框,没有richtextbox ..

标签: arrays vb.net compare


【解决方案1】:

使用 Linq Except 扩展:

Dim diffs = txt1.Except(txt2)

输出:

  • diffs(0) = "他"
  • diffs(1) = "男孩"

你可以在 txt1 和 txt2 之间交换:

Dim diffs = txt2.Except(txt1)

输出:

  • diffs(0) = "她"
  • diffs(1) = "女孩"

【讨论】:

  • Thx..它让我知道如何做......我做的方式是` For i = 0 To txt2.Length - 1 If txt2(i) txt1(i) Then diff1 += txt1(i).ToString & " " End If Next i `
【解决方案2】:

这种方式也可以使用

    Dim txt1(TextBox1.Text.Split(" ").Length) As String
    Dim txt2(TextBox2.Text.Split(" ").Length) As String
    txt1 = TextBox1.Text.Split(" ")
    txt2 = TextBox2.Text.Split(" ")
    Dim diff1 As String = "" 'Differences between 1 and 2
    Dim diff2 As String = "" 'Differences between 2 and 1

    For i = 0 To txt2.Length - 1
        If txt2(i) <> txt1(i) Then
            diff1 += txt1(i).ToString & "  "

        End If

    Next i

    For x = 0 To txt1.Length - 1
        If txt1(x) <> txt2(x) Then
            diff2 += txt2(x).ToString & "  "
        End If

    Next x

【讨论】:

    猜你喜欢
    • 2014-04-02
    • 1970-01-01
    • 2010-10-31
    • 2022-10-17
    • 2011-02-02
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多