比较两个文本框中的单词以找到差异?

时间:2015-05-21 09:35:40

标签: arrays vb.net compare

我有2个TextBox。

我想将Textbox1的所有单词与Textbox2进行比较

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

示例:

专栏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

我也面临一个无法突出显示文字的问题

2 个答案:

答案 0 :(得分:3)

使用Linq Except扩展程序:

Dim diffs = txt1.Except(txt2)

输出:

  
      
  • diffs(0)=“he”
  •   
  • diffs(1)=“boy”
  •   

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

Dim diffs = txt2.Except(txt1)

输出:

  
      
  • diffs(0)=“她”
  •   
  • diffs(1)=“girl”
  •   

答案 1 :(得分:0)

也可以这样使用

    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