如何比较两个字符串并使用C#Code找到差异

时间:2017-09-23 07:47:00

标签: c#

我想比较两个字符串

string1 = "My Name is Something. I do nothing"
string2 = "My Name is Momething. I do othing"

结果应该是 “我的名字是 Momething 。我做 othing

单词中的差异应以不同的字体或颜色显示

我试过

var difference = string1.Except(string2).ToArray()    

给出差异数组

4 个答案:

答案 0 :(得分:3)

对集合使用Except将获取第一个集合中的所有项目,但第二个集合除了(通过类型相等)项目。由于您的类型为string,因此它们是char的集合。您不希望Except但要检查哪些字词不同。

使用Split获取字符串集合,其中每个字符串都是一个单词,然后使用Zip来比较句子中相同位置的单词:

var string1 = "My Name is Something. I do nothing";
var string2 = "My Name is Momething. I do othing";

var result = string1.Split(' ').Zip(string2.Split(' '), (s1, s2) => new { s1, s2 })
                    .Where(p => p.s1 != p.s2);

如果你想确保你没有只有空格的部分,你也可以像这样分开:

Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)

要将其重新标记为单个字符串并标记差异(例如将其与<b>围绕html粗体,您可以执行此操作:

var result = string.Join(" ", string1.Split(' ')
                       .Zip(string2.Split(' '), (s1, s2) => new { s1, s2 })
                       .Select(pair => pair.s1 != pair.s2 ? $"<b>{pair.s2}</b>" : pair.s1));

答案 1 :(得分:0)

试试这个,这个代码逐字逐句比较,如果你的字符串没有相同的单词数字,则相同:

string string1 = "My Name is Something. I do nothing tessst";
string string2 = "My Name is Momething. I do othing";

//Trasnforme string to list with space like separator, and compare string by position
var List1 = string1.Split(' ').Select((valuestring1, index) => new { valuestring1, index });
var List2 = string2.Split(' ').Select((valuestring2, index) => new { valuestring2, index });

//Left outer join
var leftdifference = from word1 in List1
                     from word2 in List2.Where(word2 => word1.index == word2.index).DefaultIfEmpty()
                     where word2 == null || word1.valuestring1 != word2.valuestring2
                     select new { word1, word2 };

//Right outer join
var rightdifference = from word2 in List2
                      from word1 in List1.Where(word1 => word1.index == word2.index).DefaultIfEmpty()
                     where word1 == null || word1.valuestring1 != word2.valuestring2
                      select new { word1, word2 };

var fulldifference = leftdifference.Union(rightdifference).ToList();

foreach (var item in fulldifference)
{
    string val1 = item.word1 == null ? "NOT PRESENT WORD" : item.word1.valuestring1;
    string val2 = item.word2 == null ? "NOT PRESENT WORD" : item.word2.valuestring2;
    int index = item.word1 == null ? item.word2.index : item.word1.index;

    Console.WriteLine("position {0}, string1 : '{1}' , string2 : '{2}'", index, val1, val2);
}

答案 2 :(得分:0)

我不知道你是在网络上还是其他方面尝试这个,对于控制台应用程序:

string[] strArr1 = string1.Split(' ').ToArray();
string[] strArr2 = string2.Split(' ').ToArray();

for (int i = 0; i < strArr1.Length; i++)
{
    if(string.Compare(strArr1[i], strArr2[i]) != 0)
    {
        Console.BackgroundColor = ConsoleColor.Blue;
        Console.ForegroundColor = ConsoleColor.White;
        Console.Write(strArr2[i]);
        Console.ResetColor();
        Console.Write(" ");
    }
    else
    {
        Console.Write(strArr2[i] + " ");
        Console.Write(" ");
    }
}

答案 3 :(得分:0)

可能是最简单的方法

        String[] str1 = "foo foo ffo foo".Split(' ');
        String[] str2 = "foo foo foo foo".Split(' ');
        //if you want to push differences to a list just uncomment TODO lines
        //List<String> result = new List<String>(); TODO

        //int index = 0; TODO
        for(int i = 0; i < str1.Length; i++)
        {
            if (str1[i] != str2[i])
            {
                //str2[i] here is a different word
                //result.Add(str2[i]); TODO
                //index++; TODO 
            }
        }