In 1965 Vladmir Levenshtein created a distance algorithm. This tells us the number of edits needed to turn one string into another. With Levenshtein distance, we measure similarity and match approximate strings with fuzzy logic.

Info:Returns the number of character edits (removals, inserts, replacements) that must occur to get from string A to string B.

Example

First, credit at the conceptual level goes to Vladimir Levenshtein, a Russian scientist. This code uses a two-dimensional array instead of a jagged array because the space required will only have one width and one height.

Tip:The two-dimensional array requires fewer allocations upon the managed heap and may be faster in this context.

The Levenshtein method is static—this Compute method doesn't need to store state or instance data, which means you can declare it as static. This can also improve performance, avoiding callvirt instructions.

Tip:You can verify the implementation is the standard version of Levenshtein by looking at a computer science textbook.

This algorithm is stateless, which means it doesn't store instance data. It therefore can be put in a static class. Static classes are easier to add to new projects than separate methods. Static-class.

Example 2

Continuing on, we call the method. You will often want to compare multiple strings with the Levenshtein algorithm. The example here shows how to compare strings in a loop. We use a List of string arrays.

Summary

With the Levenshtein distance algorithm, we implement approximate string matching. The difference between two strings is not represented as true or false, but as the number of steps needed to get from one to the other.