C#C
C#4y ago
Bujju

Levenshtein distance method throwing `IndexOutOfRangeException` [Answered]

I have this code to calculate levenshtein distance:

public static int CompareStrings(string string1, string string2)
{
    if (string.IsNullOrEmpty(string1) && string.IsNullOrEmpty(string2)) return 0;
    if (string.IsNullOrEmpty(string1)) return string2.Length;
    if (string.IsNullOrEmpty(string2)) return string1.Length;

    if (string1.Length > string2.Length)
    {
        string temp = string1;

        string1 = string2;
        string2 = temp;
    }

    var distances = new int[string1.Length + 1, string2.Length + 1];
    for (int i = 0; i <= string1.Length; i++)
    {
        for (int j = 1; i <= string2.Length; j++)
        {
            int a = Math.Min(distances[i - 1, j] + 1, distances[i, j - 1] + 1);
            int b = string2[j - 1] == string1[i - 1] ? 0 : 1;

            distances[i, j] = Math.Min(a, b);
        }
    }

    return distances[string1.Length, string2.Length];
}


When string1 is empty and string2 is "Example", it works.

When string1 is "Ex" and string2 is "Example", it throws an IndexOutOfRangeException.
Was this page helpful?