C#如何比较两个词串并指出哪些部分不同 [英] C# How can I compare two word strings and indicate which parts are different
问题描述
例如,如果我有...
string a = "personil";
string b = "personal";
我想得到...
string c = "person[i]l";
但是它不一定是单个字符.我也可以这样...
However it is not necessarily a single character. I could be like this too...
string a = "disfuncshunal";
string b = "dysfunctional";
对于这种情况,我想得到...
For this case I would want to get...
string c = "d[isfuncshu]nal";
另一个例子是...(注意两个词的长度不同.)
Another example would be... (Notice that the length of both words are different.)
string a = "parralele";
string b = "parallel";
string c = "par[ralele]";
另一个例子是...
string a = "ato";
string b = "auto";
string c = "a[]to";
我该怎么做?
两个字符串的长度可以不同.
The length of the two strings can be different.
添加了其他示例.感谢用户 Nenad 的询问.
Added additional examples. Credit goes to user Nenad for asking.
推荐答案
我今天一定很无聊,但我实际上制作了通过所有 4 个案例的 UnitTest(如果您在此期间没有添加更多).
I must be very bored today, but I actually made UnitTest that pass all 4 cases (if you did not add some more in the meantime).
编辑:添加了 2 个边缘情况并修复它们.
Edit: Added 2 edge cases and fix for them.
Edit2:重复多次的字母(以及这些字母上的错误)
Edit2: letters that repeat multiple times (and error on those letters)
[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#如何比较两个词串并指出哪些部分不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!