首页 > 解决方案 > 在C#中比较两个不同长度的字符串中的字符

问题描述

在 C# 中,我试图比较两个字符串并找出有多少字符不同。

我试过这个:

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
}

但这有问题:

  1. 如果字符串包含相同的字符但在字符串中的不同位置
  2. 它消除了重复的出现

如果字符串的长度相同,我会一一比较字符,但如果一个大于另一个,则位置不同

标签: c#string

解决方案


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

推荐阅读