比较两个richtextbox中的单词来找到差异?

时间:2014-03-01 10:25:29

标签: vb.net loops compare richtextbox highlight

我有三个RichTextBoxes。我希望将RichTextbox1Richtextbox2的所有单词逐一进行比较,并以空格或逗号作为分隔符。

如果它们相同则不执行任何操作,如果不将文本突出显示为某种颜色并将其保存在RichTextBox3中。

我在循环方面遇到了一些麻烦。

2 个答案:

答案 0 :(得分:1)

解释

首先,我们将声明一些变量来缩短我们的写作工作。然后我们将使用For Each命令。

在这里,我们将进行两轮扫描差异,首先是Richtextbox1,而不是Richtextbox2,反之亦然。不同的字符会不断添加到变量diff1diff 2,最后我们将在RichTextbox3中编译它们。

它适用于diff算法。

代码和示例

Dim txt1(RichTextBox1.Text.Split(" ").Length) As String
Dim txt2(RichTextBox2.Text.Split(" ").Length) As String
txt1 = RichTextBox1.Text.Split(" ")
txt2 = RichTextBox2.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
    RichTextbox3.Text = diff1 & diff2
End Sub

希望它能完美运作!

答案 1 :(得分:0)

  

有人可以帮我染色文字吗? - Vineet Kamath 3月1日17:30

如果要为文本着色或突出显示,只需要(1)查找并选择单词/字符串,然后(2)设置文本属性。

尝试以这种方式修改Error404的代码:

Dim diffPosition as integer ' Set where beging to find and select in RichTextBox
diffPosition = 1 ' Initialize

For Each diff As String In txt1
   If Array.IndexOf(txt2, diff.ToString) = -1 Then
        diff1 += diff.ToString & " "
        With RichTextBox1
             .Find(diff, diffPosition, RichTextBoxFinds.None) ' Find and select diff in RichTextBox1 starting from position diffPosition in RichtextBox1
             .SelectionFont = New Font(.Font, FontStyle.Bold) ' Set diff in Bold
             .SelectionColor = Color.Blue ' Set diff in blue instead of black
             .SelectionBackColor = Color.Yellow ' highlight in yellow
        End With
   End If
   diffPosition = diffPosition + Len(diff) ' re-Initialize diffPostion to avoid to find and select the same text present more than once
Next

diffPosition = 1 ' re-Initialize for RichTextBox2

For Each diff As String In txt2
   If Array.IndexOf(txt1, diff.ToString) = -1 Then
        diff2 += diff.ToString & " "
        With RichTextBox2
             .Find(diff, diffPosition, RichTextBoxFinds.None) ' Find and select diff in RichTextBox2 starting from position diffPosition in RichtextBox2
             .SelectionFont = New Font(.Font, FontStyle.Bold) ' Set diff in Bold
             .SelectionColor = Color.Blue ' Set diff in blue instead of black
             .SelectionBackColor = Color.Yellow ' highlight in yellow
        End With
   End If
   diffPosition = diffPosition + Len(diff) ' re-Initialize diffPostion to avoid to find and select the same text present more than once
Next
    RichTextbox3.Text = diff1 & diff2

代码应找到并选择"差异",设置粗体样式,将每个字母的颜色设置为蓝色(而不是黑色)并以黄色突出显示。