简体   繁体   中英

Compare chars in two strings of different length in C#

In C#, Im trying to compare two strings and find out how many chars are different.

I Tried this:

static void Main(String[] args)
{
    var strOne = "abcd";
    var strTwo = "bcd";

    var arrayOne = strOne.ToCharArray();
    var arrayTwo = strTwo.ToCharArray();

    var differentChars = arrayOne.Except(arrayTwo);

    foreach (var character in differentChars)
        Console.WriteLine(character);  //Will print a
}

but there are problems with this:

  1. if the strings contain same chars but on different positions within the string
  2. it removes the duplicate occurences

If the strings would be the same length I would compare the chars one by one but if one is bigger than the other the positions are different

How about this? Append two strings into one and group them, you will have the count of the chars, > 1 will give the repeatings and = 0 will give the unique ones.

var strOne = "abcd";
var strTwo = "bcd";

var arrayOne = strOne.Concat(strTwo).GroupBy(x => x).Select(x => new { Key = x.Key, Count = x.Count() });

foreach (var character in arrayOne) {
    if (character.Count > 1)
    {
        Console.WriteLine(character.Key); // the repeating chars
    }
}

If the same character appears twice in the same string,

 var strOne = "abbcdd";
 var strTwo = "cd";

 var arrayTwo = strOne.Select(x => new { Key = x, IsExists = strTwo.Any(y => y == x) });

 foreach (var character in arrayTwo) {
     if (character.IsExists)
     {
        Console.WriteLine(character.Key);
     }
 }

You may want to have a look at the Leventshtein Distance Algorithm .

As the article says

the Levenshtein distance between two words is the minimum number of single-character edits (insertions, deletions or substitutions) required to change one word into the other

You can find many reference implementations in the internet, like here or here .

public static int LevenshteinDistance(string s, string t)
    {
        int n = s.Length;
        int m = t.Length;
        int[,] d = new int[n + 1, m + 1];

        if (n == 0)
        {
            return m;
        }

        if (m == 0)
        {
            return n;
        }

        for (int i = 0; i <= n; d[i, 0] = i++)
        {
        }

        for (int j = 0; j <= m; d[0, j] = j++)
        {
        }

        for (int i = 1; i <= n; i++)
        {
            for (int j = 1; j <= m; j++)
            {
                int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;

                d[i, j] = Math.Min(
                    Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
                    d[i - 1, j - 1] + cost);
            }
        }
        return d[n, m];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM