C#和SQL實現(xiàn)的字符串相似度計算代碼分享
更新時間:2014年10月08日 09:07:47 投稿:junjie
這篇文章主要介紹了C#和SQL實現(xiàn)的字符串相似度計算代碼分享,本文分別給出了C#語言和SQL語言的實現(xiàn)代碼,需要的朋友可以參考下
C#實現(xiàn):
復(fù)制代碼 代碼如下:
#region 計算字符串相似度
/// <summary>
/// 計算字符串相似度
/// </summary>
/// <param name="str1">字符串1</param>
/// <param name="str2">字符串2</param>
/// <returns>相似度</returns>
public static float Levenshtein(string str1, string str2)
{
//計算兩個字符串的長度。
int len1 = str1.Length;
int len2 = str2.Length;
//比字符長度大一個空間
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;
}
//計算兩個字符是否一樣,計算左上的值
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;
}
//取三個值中最小的
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個數(shù)字得到最小值
private static int Min(int i, int j, int k)
{
return i < j ? (i < k ? i : k) : (j < k ? j : k);
}
SQL實現(xiàn):
復(fù)制代碼 代碼如下:
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
--測試
--select dbo.get_semblance_By_2words('我是誰','我是誰啊')
--75
--相似度
您可能感興趣的文章:
相關(guān)文章
C#基于DBContext(EF)實現(xiàn)通用增刪改查的REST方法實例
這篇文章主要介紹了C#基于DBContext(EF)實現(xiàn)通用增刪改查的REST方法實例,是C#程序設(shè)計中非常實用的技巧,需要的朋友可以參考下2014-10-10
C#創(chuàng)建Windows Service(Windows 服務(wù))的方法步驟
本文介紹了如何用C#創(chuàng)建、安裝、啟動、監(jiān)控、卸載簡單的Windows Service 的內(nèi)容步驟和注意事項,具有一定的參考價值,感興趣的可以了解一下2023-11-11
c++函數(shù)轉(zhuǎn)c#函數(shù)示例程序分享
這篇文章主要介紹了c++函數(shù)轉(zhuǎn)c#函數(shù)示例程序,大家參考使用吧2013-12-12
unity 如何判斷鼠標(biāo)是否在哪個UI上(兩種方法)
這篇文章主要介紹了unity 判斷鼠標(biāo)是否在哪個UI上的兩種實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04

