C# 两个字符串比较并储存差异
string BeforeValue = "123456789";
string AfterValue = "321465798";
// 参数验证
if (BeforeValue == null || AfterValue == null || BeforeValue.Length != AfterValue.Length)
{
throw new ArgumentException("Invalid parameters.");
}
// 用 List 储存差异下标、两者比对的值
List<(int Index, char Before, char After)> differences = new List<(int Index, char Before, char After)>();
for (int i = 0; i < BeforeValue.Length; i++)
{
if (BeforeValue[i] != AfterValue[i])
{
differences.Add((Index: i, Before: BeforeValue[i], After: AfterValue[i]));
}
}
// 当有 BeforeValue ,AfterValue 有差异时可循环拿到对应下标和值
if (differences.Count > 0)
{
// 这里使用了 ReadOnlyCollection 来创建只读集合。它接受一个普通的 List 作为参数,并将其封装成只读集合。
ReadOnlyCollection<(int Index, char Before, char After)> readOnlyDifferences = new ReadOnlyCollection<(int Index, char Before, char After)>(differences);
StringBuilder outputBuilder = new StringBuilder();
foreach (var diff in readOnlyDifferences)
{
int diffIndex = diff.Index;
char diffBefore = diff.Before;
char diffAfter = diff.After;
outputBuilder.AppendLine($"Index: {diffIndex}, Before: {diffBefore}, After: {diffAfter}");
}
Console.WriteLine(outputBuilder.ToString());
}
请注意,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/17985134