Levenshtein Distance - CSharp System

CSharp examples for System:String Algorithm

Description

Levenshtein Distance

Demo Code


using System.Text.RegularExpressions;
using System.Linq;
using System.Globalization;
using System.Collections.Generic;
using System;/*from   ww w.  j  a v  a 2s  .c om*/

public class Main{
        public static int LevenshteinDistance(this string str, string compare, bool caseSensitive = true)
		{
			if (!caseSensitive)
			{
				str = str.ToLower();
				compare = compare.ToLower();
			}

			var sLen = str.Length;
			var cLen = compare.Length;
			var result = new int[sLen + 1, cLen + 1];

			if (sLen == 0)
				return cLen;

			if (cLen == 0)
				return sLen;

			for (int i = 0; i <= sLen; result[i, 0] = i++) ;
			for (int i = 0; i <= cLen; result[0, i] = i++) ;

			for (int i = 1; i <= sLen; i++)
			{
				for (int j = 1; j <= cLen; j++)
				{
					var cost = (compare[j - 1] == str[i - 1]) ? 0 : 1;
					result[i, j] = Math.Min(Math.Min(result[i - 1, j] + 1, result[i, j - 1] + 1), result[i - 1, j - 1] + cost);
				}
			}

			return result[sLen, cLen];
		}
}

Related Tutorials