2

I have a string that is produced by code but it may not be correct. So i have a user screen that user checks and changes it. I have to let user to change maximum of 5 characters. I need to check how many characters are changed by user with comparing two strings. length of strings may be different.

Thanx in advance. (language c#)

  • 3
    by using the [Levenshtein distance](https://stackoverflow.com/questions/9453731/how-to-calculate-distance-similarity-measure-of-given-2-strings), if the swap of 2 characters should count as one change, use the Damerau Levenshtein distance – fubo Jul 06 '18 at 13:15
  • It would be awesome if you could provide a [mcve] (of your attempt so far) with at least 15 inputs and the expected results based on those inputs. – mjwills Jul 06 '18 at 13:16
  • Consider showing example input / output. – Jeremy A. West Jul 06 '18 at 13:19
  • You could base your approach on the [Longest common subsequence](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem) – derpirscher Jul 06 '18 at 17:26

1 Answers1

2

You could compute the Levenshtein Distance between the two strings, which returns the number of character edits (removals, inserts, replacements) that must occur to get from string A to string B.

public static class LevenshteinDistance
{
    /// <summary>
    /// Compute the distance between two strings.
    /// </summary>
    public static int Compute(string s, string t)
    {
        int n = s.Length;
        int m = t.Length;
        int[,] d = new int[n + 1, m + 1];

        // Step 1
        if (n == 0) return m;
        if (m == 0) return n;

        // Step 2
        for (int i = 0; i <= n; d[i, 0] = i++);   
        for (int j = 0; j <= m; d[0, j] = j++);

        // Step 3
        for (int i = 1; i <= n; i++)
        {
            //Step 4
            for (int j = 1; j <= m; j++)
            {
                // Step 5
                int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;

                // Step 6
                d[i, j] = Math.Min(
                    Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
                    d[i - 1, j - 1] + cost);
            }
        }
        // Step 7
        return d[n, m];
    }
}

Then handle it:

if (LevenshteinDistance.Compute(s1, s2) <= 5)
    // Valid
else
    // Invalid
Matthew Steven Monkan
  • 8,170
  • 4
  • 53
  • 71