16,555
社区成员
发帖
与我相关
我的任务
分享
'比对
Private Sub btnCompare_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompare.Click
Dim i As Integer
Dim ct1, ct2 As Long
Dim num1, num2 As Integer
num1 = rtbCorrect.Lines.Length
num2 = rtbTarget.Lines.Length
If num2 < num1 Then
i = CompareLine(num2)
ct1 = CountText(rtbCorrect, i)
rtbCorrect.Select(ct1, rtbCorrect.TextLength - ct1)
rtbCorrect.SelectionColor = Color.Blue
ElseIf num1 < num2 Then
i = CompareLine(num1)
ct2 = CountText(rtbTarget, i)
rtbTarget.Select(ct2, rtbTarget.TextLength - ct2)
rtbTarget.SelectionColor = Color.Red
Else
CompareLine(num2)
End If
End Sub
'统计小于n行的richtextbox中的字数(注意每一行后面有回车符)
Private Function CountText(ByVal rtb As RichTextBox, ByVal n As Integer) As Long
Dim sum As Long = 0
If n = 0 Then
Return 0
Else
For i As Integer = 0 To n - 1
sum += rtb.Lines(i).Length + 1 '千万别忘记最后+1,回车符占位一格
Next
Return sum
End If
End Function
'行对行的比对
Private Function CompareLine(ByVal LineSum As Integer) As Integer
Dim ct1, ct2 As Integer
Dim str1, str2 As String
Dim i, j As Integer
For i = 0 To LineSum - 1
str1 = rtbCorrect.Lines(i)
str2 = rtbTarget.Lines(i)
ct1 = CountText(rtbCorrect, i)
ct2 = CountText(rtbTarget, i)
If str1 <> str2 Then
If str2.Length < str1.Length Then
For j = 0 To str2.Length - 1
If str2.Substring(j, 1) <> str1.Substring(j, 1) Then
rtbTarget.Select(j + ct2, 1)
rtbTarget.SelectionColor = Color.Red
rtbCorrect.Select(j + ct1, 1)
rtbCorrect.SelectionColor = Color.Blue
End If
Next
rtbCorrect.Select(j + ct1, str1.Length - j)
rtbCorrect.SelectionColor = Color.Blue
ElseIf str2.Length > str1.Length Then
For j = 0 To str1.Length - 1
If str2.Substring(j, 1) <> str1.Substring(j, 1) Then
rtbCorrect.Select(j + ct1, 1)
rtbCorrect.SelectionColor = Color.Blue
rtbTarget.Select(j + ct2, 1)
rtbTarget.SelectionColor = Color.Red
End If
Next
rtbTarget.Select(j + ct2, str2.Length - j)
rtbTarget.SelectionColor = Color.Red
Else
For j = 0 To str2.Length - 1
If str2.Substring(j, 1) <> str1.Substring(j, 1) Then
rtbTarget.Select(j + ct2, 1)
rtbTarget.SelectionColor = Color.Red
rtbCorrect.Select(j + ct1, 1)
rtbCorrect.SelectionColor = Color.Blue
End If
Next
End If
End If
Next
Return i
End Function