C# 如何比较两个字符串并指出哪些部分不同

rot*_*rcz 2 c# string string-comparison

例如,如果我有...

string a = "personil";
string b = "personal";
Run Code Online (Sandbox Code Playgroud)

我想得到...

string c = "person[i]l";
Run Code Online (Sandbox Code Playgroud)

然而,它不一定是单个字符。我也可以这样...

string a = "disfuncshunal";
string b = "dysfunctional";
Run Code Online (Sandbox Code Playgroud)

对于这种情况,我想得到...

string c = "d[isfuncshu]nal";
Run Code Online (Sandbox Code Playgroud)

另一个例子是......(请注意,两个单词的长度不同。)

string a = "parralele";
string b = "parallel";

string c = "par[ralele]";
Run Code Online (Sandbox Code Playgroud)

另一个例子是...

string a = "ato";
string b = "auto";

string c = "a[]to";
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?

编辑:两个字符串的长度可以不同。

编辑:添加了额外的示例。感谢用户 Nenad 的提问。

Nen*_*nad 5

我今天一定很无聊,但我实际上做了单元测试,通过了所有 4 个案例(如果您同时没有添加更多案例)。

编辑:添加了 2 个边缘情况并修复了它们。

Edit2:重复多次的字母(以及这些字母上的错误)

[Test]
[TestCase("parralele", "parallel", "par[ralele]")]
[TestCase("personil", "personal", "person[i]l")]
[TestCase("disfuncshunal", "dysfunctional", "d[isfuncshu]nal")]
[TestCase("ato", "auto", "a[]to")]
[TestCase("inactioned", "inaction", "inaction[ed]")]
[TestCase("refraction", "fraction", "[re]fraction")]
[TestCase("adiction", "ad[]diction", "ad[]iction")]
public void CompareStringsTest(string attempted, string correct, string expectedResult)
{
    int first = -1, last = -1;

    string result = null;
    int shorterLength = (attempted.Length < correct.Length ? attempted.Length : correct.Length);

    // First - [
    for (int i = 0; i < shorterLength; i++)
    {
        if (correct[i] != attempted[i])
        {
            first = i;
            break;
        }
    }

    // Last - ]
    var a = correct.Reverse().ToArray();
    var b = attempted.Reverse().ToArray();
    for (int i = 0; i < shorterLength; i++)
    {
        if (a[i] != b[i])
        {
            last = i;
            break;
        }
    }

    if (first == -1 && last == -1)
        result = attempted;
    else
    {
        var sb = new StringBuilder();
        if (first == -1)
            first = shorterLength;
        if (last == -1)
            last = shorterLength;
        // If same letter repeats multiple times (ex: addition)
        // and error is on that letter, we have to trim trail.
        if (first + last > shorterLength)
            last = shorterLength - first;

        if (first > 0)
            sb.Append(attempted.Substring(0, first));

        sb.Append("[");

        if (last > -1 && last + first < attempted.Length)
            sb.Append(attempted.Substring(first, attempted.Length - last - first));

        sb.Append("]");

        if (last > 0)
            sb.Append(attempted.Substring(attempted.Length - last, last));

        result = sb.ToString();
    }
    Assert.AreEqual(expectedResult, result);
}
Run Code Online (Sandbox Code Playgroud)