Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

advance C# string comparison

Tags:

c#

.net

windows

Is there any class (function) in .Net that can do this:

if s1 = " I have a black car" and s2 = "I have a car that is small";
int matchingProcentage = matchingFunction(s1,s2);

  matchingProcentage == 70% <-- just as an example value :)
like image 898
angela d Avatar asked Nov 30 '22 07:11

angela d


2 Answers

Here's a good way of going about it!

Levenshtein Distance

like image 90
Bengel Avatar answered Dec 04 '22 15:12

Bengel


A function like the following should work, it was hastily written so feel free to change things up:

Usage:

GetStringPercentage("I have a black car", "I have a car that is small");

Method:

public static decimal GetStringPercentage(string s1, string s2)
{
     decimal matches = 0.0m;
     List<string> s1Split = s1.Split(' ').ToList();
     List<string> s2Split = s2.Split(' ').ToList();

     if (s1Split.Count() > s2Split.Count())
     {
         foreach (string s in s1Split)
             if (s2Split.Any(st => st == s))
                 matches++;

             return (matches / s1Split.Count());
     }
     else
     {
         foreach (string s in s2Split)
             if (s1Split.Any(st => st == s))
                  matches++;

         return (matches / s2Split.Count());
     }

}
like image 35
Rion Williams Avatar answered Dec 04 '22 14:12

Rion Williams