C#计算两字符串相似度
|
admin
2023年3月22日 15:40
本文热度 1812
|
动态规划相似度算法经常被用来确定两个字符串文本是否相似,特别是在模糊匹配搜索中。下面封装的C#.NET函数采用动态规划法比较两个短文本之间的相似度,返回百分比(精确道小数点两位)。

private void button1_Click(object sender, EventArgs e)
{
this.textBox3.Text = "相似度:" + ComputeTextSame(this.textBox1.Text, this.textBox2.Text, false).ToString();
}
public static double ComputeTextSame(string textX, string textY, bool isCase = false)
{
if (textX.Length <= 0 || textY.Length <= 0)
{
return (0);
}
if (!isCase)
{
textX = textX.ToLower();
textY = textY.ToLower();
}
int[,] dp = new int[Math.Max(textX.Length, textY.Length) + 1, Math.Max(textX.Length, textY.Length) + 1];
for (int x = 0; x < textX.Length; x++)
{
for (int y = 0; y < textY.Length; y++)
{
if (textX[x] == textY[y])
{
dp[x + 1, y + 1] = dp[x, y] + 1;
}
else
{
dp[x + 1, y + 1] = Math.Max(dp[x, y + 1], dp[x + 1, y]);
}
}
}
return (Math.Round(((double)(dp[textX.Length, textY.Length]) / Math.Max(textX.Length, textY.Length)) * 100, 2));
}
该文章在 2025/2/24 14:43:16 编辑过