我有三个RichTextBoxes
。我想用空格或逗号作为分隔符一一比较RichTextbox1
的所有单词Richtextbox2
。
如果它们相同,则不执行任何操作,如果不将文本突出显示为某种颜色并将其保存在RichTextBox3
中。
我在循环中遇到了一些问题。
解释
首先,我们将声明一些变量来缩短我们的写作工作。然后,我们将使用 For Each 命令。
在这里,我们将进行两轮扫描差异,首先Richtextbox1
不在Richtextbox2
中,反之亦然。不同的字符将继续添加到变量diff1
和diff 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
希望它能完美运行!
有人可以帮我给文字上色吗? – 维内特·卡马斯 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
代码应查找并选择"diff",设置粗体样式,将每个字母的颜色设置为蓝色(而不是黑色)并以黄色突出显示。