c中的文本比较结果
本文关键字:结果 文本比较 | 更新日期: 2023-09-27 18:20:40
我想比较两个文本字符串(nvarchar字符)&想要找到他们的比较结果。示例:
string 1: We loved our country.it is beautiful and amazing too.
string 2: We loved our nice country.it is beautifully amazing too.
预期结果:
No. of change: 3
they are: nice,beautifully,and.
我试过了:
private string TextComparison(string textFirst,string textSecond)
{
Difference difference = new Difference();
return result = difference.DifferenceMain(textFirst, textSecond);
}
我需要一个函数DifferenceMain()
。
试试这个
string st1 = "We loved our country.it is beautiful and amazing too";
string st2 = "We loved our nice country.it is beautifully amazing too";
List<string> diff;
List<string> diff1;
IEnumerable<string> str1 = st1.Split(' ').Distinct();
IEnumerable<string> str2 = st2.Split(' ').Distinct();
diff = str2.Except(str1).ToList();
diff1 = str1.Except(str2).ToList();
diff将给出以下结果
不错
美丽
_(空格)-因为你的第二个字符串包含额外的空格
diff1将给出以下结果
美丽
使用此函数。
public string[] GetChanges(string one, string two)
{
string[] wordsonone = one.Split(" ".ToCharArray());//Creates a string array by splitting the string into individual words.
string[] wordsontwo = two.Split(" ".ToCharArray());
List<string> changes = new List<string>();//Create a string list to contain all the changes.
for(int i = 0; i < wordsonone.Length; i++)
{
if(!wordsontwo.Contains(wordsonone[i]))//If wordsontwo doesn't contain this word.
{
changes.Add(wordsonone[i]);//Add this word to changes
}
}
for (int i = 0; i < wordsontwo.Length; i++)
{
if(!wordsonone.Contains(wordsontwo[i]))
{
changes.Add(wordsontwo[i]);
}
}
return changes.ToArray();
}
为了以您的格式呈现它,您需要使用以下内容。
string[] changes = GetChanges(string1,string2);
string text = "Numbers of Changes "+changes.Length+", these changes are ";
foreach(string change in changes)
{
text += change+", ";
}
MessageBox.Show(text);