gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:11:52 25 4
gpt4 key购买 nike

例如,如果我有...

string a = "personil";
string b = "personal";

我想得到...

string c = "person[i]l";

但不一定是单个字符。我也可以这样……

string a = "disfuncshunal";
string b = "dysfunctional";

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

string c = "d[isfuncshu]nal";

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

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

string c = "par[ralele]";

另一个例子是...

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

string c = "a[]to";

我该怎么做?

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

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

最佳答案

我今天一定很无聊,但我实际上做了 UnitTest 并通过了所有 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);
}

关于C#如何比较两个字符串并指出哪些部分不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15301481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com