c#中的文本比较结果

时间:2015-11-04 13:58:52

标签: c#

我想比较两个文本字符串(nvarchar字符)&想找到他们的比较结果。 例如:

Array.prototype.slice.call(document.getElementsByClassName("myClass")).forEach(function(elem,index) {
    elem.style.left = 100px;
});

预期结果:

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); }

2 个答案:

答案 0 :(得分:2)

试试这个

        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(); 

差异会给你以下结果
不错
精美
_(空格) - 因为你的第二个字符串包含额外的空格

diff1 会给你以下结果
美丽

答案 1 :(得分:0)

使用此功能。

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);