C#和SQL實(shí)現(xiàn)的字符串相似度計(jì)算代碼分享
C#實(shí)現(xiàn):
#region 計(jì)算字符串相似度
/// <summary>
/// 計(jì)算字符串相似度
/// </summary>
/// <param name="str1">字符串1</param>
/// <param name="str2">字符串2</param>
/// <returns>相似度</returns>
public static float Levenshtein(string str1, string str2)
{
//計(jì)算兩個(gè)字符串的長(zhǎng)度。
int len1 = str1.Length;
int len2 = str2.Length;
//比字符長(zhǎng)度大一個(gè)空間
int[,] dif = new int[len1 + 1, len2 + 1];
//賦初值,步驟B。
for (int a = 0; a <= len1; a++)
{
dif[a, 0] = a;
}
for (int a = 0; a <= len2; a++)
{
dif[0, a] = a;
}
//計(jì)算兩個(gè)字符是否一樣,計(jì)算左上的值
int temp;
for (int i = 1; i <= len1; i++)
{
for (int j = 1; j <= len2; j++)
{
if (str1.Substring(i - 1, 1) == str2.Substring(j - 1, 1))
{
temp = 0;
}
else
{
temp = 1;
}
//取三個(gè)值中最小的
dif[i, j] = Min(dif[i - 1, j - 1] + temp, dif[i, j - 1] + 1, dif[i - 1, j] + 1);
}
}
return 1 - (float)dif[len1, len2] / Math.Max(str1.Length, str2.Length);
}
#endregion
//比較3個(gè)數(shù)字得到最小值
private static int Min(int i, int j, int k)
{
return i < j ? (i < k ? i : k) : (j < k ? j : k);
}
SQL實(shí)現(xiàn):
CREATE function get_semblance_By_2words
(
@word1 varchar(50),
@word2 varchar(50)
)
returns nvarchar(4000)
as
begin
declare @re int
declare @maxLenth int
declare @i int,@l int
declare @tb1 table(child varchar(50))
declare @tb2 table(child varchar(50))
set @i=1
set @l=2
set @maxLenth=len(@word1)
if len(@word1)<len(@word2)
begin
set @maxLenth=len(@word2)
end
while @l<=len(@word1)
begin
while @i<len(@word1)-1
begin
insert @tb1 (child) values( SUBSTRING(@word1,@i,@l) )
set @i=@i+1
end
set @i=1
set @l=@l+1
end
set @i=1
set @l=2
while @l<=len(@word2)
begin
while @i<len(@word2)-1
begin
insert @tb2 (child) values( SUBSTRING(@word2,@i,@l) )
set @i=@i+1
end
set @i=1
set @l=@l+1
end
select @re=isnull(max( len(a.child)*100/ @maxLenth ) ,0) from @tb1 a, @tb2 b where a.child=b.child
return @re
end
GO
--測(cè)試
--select dbo.get_semblance_By_2words('我是誰(shuí)','我是誰(shuí)啊')
--75
--相似度
相關(guān)文章
C#基于DBContext(EF)實(shí)現(xiàn)通用增刪改查的REST方法實(shí)例
這篇文章主要介紹了C#基于DBContext(EF)實(shí)現(xiàn)通用增刪改查的REST方法實(shí)例,是C#程序設(shè)計(jì)中非常實(shí)用的技巧,需要的朋友可以參考下2014-10-10
c#基于NVelocity實(shí)現(xiàn)代碼生成
這篇文章主要介紹了c#基于NVelocity實(shí)現(xiàn)代碼生成的方法,幫助大家更好的理解和使用c#,感興趣的朋友可以了解下2021-01-01
C# [ImportDll()] 知識(shí)小結(jié)
今天小編就為大家分享一篇關(guān)于C# [ImportDll()] 知識(shí)小結(jié),小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-01-01
C#創(chuàng)建Windows Service(Windows 服務(wù))的方法步驟
本文介紹了如何用C#創(chuàng)建、安裝、啟動(dòng)、監(jiān)控、卸載簡(jiǎn)單的Windows Service 的內(nèi)容步驟和注意事項(xiàng),具有一定的參考價(jià)值,感興趣的可以了解一下2023-11-11
c++函數(shù)轉(zhuǎn)c#函數(shù)示例程序分享
這篇文章主要介紹了c++函數(shù)轉(zhuǎn)c#函數(shù)示例程序,大家參考使用吧2013-12-12
C#實(shí)現(xiàn)動(dòng)態(tài)生成表格的方法
這篇文章主要介紹了C#實(shí)現(xiàn)動(dòng)態(tài)生成表格的方法,是C#程序設(shè)計(jì)中非常實(shí)用的技巧,需要的朋友可以參考下2014-09-09
unity 如何判斷鼠標(biāo)是否在哪個(gè)UI上(兩種方法)
這篇文章主要介紹了unity 判斷鼠標(biāo)是否在哪個(gè)UI上的兩種實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-04-04

