c# - 在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
}
但这有问题:
- 如果字符串包含相同的字符但在字符串中的不同位置
- 它消除了重复的出现
如果字符串的长度相同,我会一一比较字符,但如果一个大于另一个,则位置不同
解决方案
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];
}
}
推荐阅读
- wordpress - 如何在图库中查看网站模板?
- ckeditor - CKEditor 4 - cannot replace selection
- c# - 如何从 IIS 绑定中获取 IP 地址
- angular - 输入 url 时 canActivate 不起作用
- c# - 创建等待任务以发送消息
- javascript - 时刻js添加功能不起作用
- r - 如何使用 project-lib 将 csv 文件保存到云对象存储?
- ruby-on-rails - 更改具有子节点的现有节点的父节点
- android - Android - 滚动视图内的自动滚动线性布局?
- azure - 如何为 azure 自定义连接器或 azure 函数设置邮件正文大小限制