Home > Mobile >  how to comparing two slightly different strings and return Percent likeness between the two strings
how to comparing two slightly different strings and return Percent likeness between the two strings

Time:01-30

I need to comparing two slightly different strings and return Percent likeness between the two strings This could have been easier for two strings of same length. But what if the length is different? For Example :

I like to help everybody
Hi I would like to help every coder 

A simple logic would be to compare each word in first sentence with same position word of different sentence. But in this case the length is different. So how do I proceed?

Any help would be appreciated.

CodePudding user response:

The problem you're describing is generally known as the string similarity problem and there existing multiple implementations of it, AFAIK, with probably the most well known being the Levenshtein distance algorithm:

https://en.wikipedia.org/wiki/Levenshtein_distance

For others, refer for example to this article: https://itnext.io/string-similarity-the-basic-know-your-algorithms-guide-3de3d7346227

CodePudding user response:

Levenshtein Distance is a good metric to judge how close two strings are

here is an implementation of Levenshtein Distance in JS from

https://www.30secondsofcode.org/js/s/levenshtein-distance

const levenshteinDistance = (s, t) => {
  if (!s.length) return t.length;
  if (!t.length) return s.length;
  const arr = [];
  for (let i = 0; i <= t.length; i  ) {
    arr[i] = [i];
    for (let j = 1; j <= s.length; j  ) {
      arr[i][j] =
        i === 0
          ? j
          : Math.min(
              arr[i - 1][j]   1,
              arr[i][j - 1]   1,
              arr[i - 1][j - 1]   (s[j - 1] === t[i - 1] ? 0 : 1)
            );
    }
  }
  return arr[t.length][s.length];
};

Usage: levenshteinDistance('duck', 'dark'); // 2

Another implementation of Levenshtein Distance which lets you have the match in ratio/percentage

https://github.com/nol13/fuzzball.js/

  • Related