© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
24 replies
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];
}
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
string1
is empty and
string2
string2
is "Example", it works.

When
string1
string1
is "Ex" and
string2
string2
is "Example", it throws an
IndexOutOfRangeException
IndexOutOfRangeException
.
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ ✅ IndexOutOfRangeException
C#CC# / help
3y ago
✅ System.IndexOutOfRangeException
C#CC# / help
2y ago
IndexOutOfRangeException? Why??
C#CC# / help
2y ago