-1

I have 2 names that i have fetched from my database.

string query1 = SELECT FIRSTNAME FROM STUDENT;
string query2 = SELECT FIRSTNAME FROM CUSTOMER;

The result from query1 is say RESET and the result from query2 is for example SET. i want to compare the 2 strings and get the match as an integer and calculate the percentage. In the example above the match is 3. so the % will be 3/5 * 100. which C# function can i use to compare the strings? i want to do the comparison in C# code and not using SQL.

Lawrence
  • 485
  • 3
  • 8
  • 22
  • It isn't clear how should the match be done... Substring? Character by character? SR is a match of RESET? Give some examples. – xanatos Mar 03 '15 at 12:21
  • 1
    As written in the linked other question, you need to give us the [String metric](http://en.wikipedia.org/wiki/String_metric) – xanatos Mar 03 '15 at 12:22
  • 1
    Not certain, but looks like you're basically taking total - Levenshtein distance and then calculating the percentage? – Robert Mar 03 '15 at 12:26
  • @xanatos an matching character by character – Lawrence Mar 03 '15 at 12:41

2 Answers2

0

Given two strings, S of length n and R of length m, where n < m, you could do something like

float percentage = 0;
int index = R.substring(S);
if(index > 0) {
    percentage = R.Length / S.Length * 100;
}
chiaboy
  • 394
  • 2
  • 6
0

This will check if a string is a substring of another string (as given in your example RESET vs SET). Note that it's reflexive, so RESET vs SET == SET vs RESET. If you need to check for substrings (so RESE vs SET == 2/4 == 0.5 or something else) then you'll need to explain what you want.

public static double Percentage(string str1, string str2) {
    // Handling of empty strings. No divisions by zero here!
    if (string.IsNullOrEmpty(str1) || string.IsNullOrEmpty(str2)) {
        return 0.0;
    }

    // str2 is contained in str1
    if (str1.Contains(str2)) {
        return 100.0 * str2.Length / str1.Length;
    }

    // str1 is contained in str2
    if (str2.Contains(str1)) {
        return 100.0 * str1.Length / str2.Length;
    }

    // No matching
    return 0.0;
}
xanatos
  • 109,618
  • 12
  • 197
  • 280