查找两个字符串之间的不常见字符

时间:2018-04-17 13:37:55

标签: c# c#-4.0

我有以下代码:

public static void Main (string[] args) {
    string word1 = "AN";
    string word2 = "ANN";

    //First try:
    var intersect = word1.Intersect(word2); 
    var unCommon1 = word1.Except(intersect).Union(word2.Except(intersect));

    //Second try:
    var unCommon = word1.Except(word2).Union(word2.Except(word1));              
  }

我想要获得的结果是N。我通过阅读在线帖子尝试了几种方法来获取它,我无法弄明白。有没有办法使用linq在两个字符串之间获得不常见的字符。

字符串中的字符顺序无关紧要。 以下是几个场景: FOO& BAR将产生F,O,O,B,A,R。 人工神经网络NAN将导致空字符串。

1 个答案:

答案 0 :(得分:2)

这是一个直接的LINQ函数。

string word1 = "AN";
string word2 = "ANN";

//get all the characters in both strings
var group = string.Concat(word1, word2)

    //remove duplicates
    .Distinct()

    //count the times each character appears in word1 and word2, find the
    //difference, and repeat the character difference times
    .SelectMany(i => Enumerable.Repeat(i, Math.Abs(
        word1.Count(j => j == i) - 
        word2.Count(j => j == i))));