Calculates the levenshtein distance and returns a ratio to a long string.
Code
/// <Summary>
/// Levenshtein distance
/// </Summary>
Static class stringext
{
/// <Summary>
/// Calculate the difference distance between two strings
/// </Summary>
/// <Param name = "Source"> source string </param>
/// <Param name = "target"> Target string </param>
/// <Returns> string gap </returns>
Public static int calcdistance (this string source, string target)
{
Int n = source. length;
Int M = target. length;
If (M = 0) return N;
If (n = 0) return m;
VaR matrix = new int [n + 1, m + 1];
For (INT I = 1; I <= N; I ++)
{
Matrix [I, 0] = I;
}
For (INT I = 1; I <= m; I ++)
{
Matrix [0, I] = I;
}
For (INT I = 1; I <= N; I ++)
{
VaR Si = source [I-1];
For (Int J = 1; j <= m; j ++)
{
VaR TJ = target [J-1];
Int cost;
If (SI = TJ)
Cost = 0;
Else
Cost = 1;
Int above = matrix [I-1, J] + 1;
Int left = matrix [I, j-1] + 1;
Int diag = matrix [I-1, J-1] + cost;
Matrix [I, j] = math. Min (above, math. Min (left, DIAG ));
}
}
Return matrix [n, m];
}
/// <Summary>
/// Calculate the similarity between two strings
/// </Summary>
/// <Param name = "Source"> source string </param>
/// <Param name = "target"> Target string </param>
/// <Returns> similarity </returns>
Public static double calcsimilarity (this string source, string target)
{
Int n = source. length;
Int M = target. length;
If (n = 0 | M = 0)
Return 0;
Int distance = source. calcdistance (target );
Int max = math. Max (n, m );
Return 1.0 * (max-distance)/max;
}
}