Visual Basic 两个字符串比较并储存差异
Dim BeforeValue As String = "123456789"
Dim AfterValue As String = "321465798"
' 参数验证
If BeforeValue Is Nothing OrElse AfterValue Is Nothing OrElse BeforeValue.Length <> AfterValue.Length Then
Throw New ArgumentException("Invalid parameters.")
End If
' 用 List 储存差异下标、两者比对的值
Dim differences As New List(Of (Index As Integer, Before As Char, After As Char))()
For i As Integer = 0 To BeforeValue.Length - 1
If BeforeValue(i) <> AfterValue(i) Then
differences.Add((Index:=i, Before:=BeforeValue(i), After:=AfterValue(i)))
End If
Next
' 当有 BeforeValue ,AfterValue 有差异时可循环拿到对应下标和值
If differences.Count > 0 Then
'这里使用了 ReadOnlyCollection 来创建只读集合。它接受一个普通的 List 作为参数,并将其封装成只读集合。
Dim readOnlyDifferences As New ReadOnlyCollection(Of (Index As Integer, Before As Char, After As Char))(differences)
Dim outputBuilder As New StringBuilder()
For Each diff In readOnlyDifferences
Dim diffIndex As Integer = diff.Index
Dim diffBefore As Char = diff.Before
Dim diffAfter As Char = diff.After
outputBuilder.AppendLine($"Index: {diffIndex}, Before: {diffBefore}, After: {diffAfter}")
Next
Console.WriteLine(outputBuilder.ToString())
End If
请注意,ReadOnlyCollection 是只读的,因此不能对其进行修改。这意味着无法通过 readOnlyDifferences.Add() 或 readOnlyDifferences.RemoveAt() 等方法来修改集合。它只是提供了一个只读的视图,以确保数据的不可变性。
运行结果:
Index: 0, Before: 1, After: 3
Index: 2, Before: 3, After: 1
Index: 4, Before: 5, After: 6
Index: 5, Before: 6, After: 5
Index: 7, Before: 8, After: 9
Index: 8, Before: 9, After: 8
本文来自博客园,作者:苏沐~,转载请注明原文链接:https://www.cnblogs.com/sumu80/p/17984693