问题
I am new to C#. I have 2 strings, they are representing characters from International Phonetic Alphabet.
String 1 - ðə ɻɛd fɑks ɪz hʌŋgɻi
String 2 - ðæt ɪt foks ɪn ðʌ sʌn ɻe͡i
Now I need to compare String 1
with String 2
and find how much String 2
differ from String 1
. I need this value as a percentage value. How can I do this? Small code example will help me a lot. Your help will be greatly appreciated.
回答1:
You should have tell what is your String Metric
Also, have a look in this How to find difference between two strings - C# question.
This will compare char by char, it is different than Llevenshtein Distance which is more common when comparing string differences.
void Main()
{
string str1 = "ðə ɻɛd fɑks ɪz hʌŋgɻi";
string str2 = "ðæt ɪt foks ɪn ðʌ sʌn ɻe͡i";
Console.WriteLine(StringCompare(str1,str2)); //34.6153846153846
Console.WriteLine(StringCompare("same","same")); //100
Console.WriteLine(StringCompare("","")); //100
Console.WriteLine(StringCompare("","abcd")); //0
}
static double StringCompare(string a, string b)
{
if (a == b) //Same string, no iteration needed.
return 100;
if ((a.Length == 0) || (b.Length == 0)) //One is empty, second is not
{
return 0;
}
double maxLen = a.Length > b.Length ? a.Length: b.Length;
int minLen = a.Length < b.Length ? a.Length: b.Length;
int sameCharAtIndex = 0;
for (int i = 0; i < minLen; i++) //Compare char by char
{
if (a[i] == b[i])
{
sameCharAtIndex++;
}
}
return sameCharAtIndex / maxLen * 100;
}
回答2:
Something along the lines of
string str1 = "ðə ɻɛd fɑks ɪz hʌŋgɻi";
string str2 = "ðæt ɪt foks ɪn ðʌ sʌn ɻe͡i";
char[] str1Char = str1.ToCharArray();
char[] str2Char = str2.ToCharArray();
int matchCount = 0;
int unmatchedCount = 0;
for (int x = 0; x>= str1Char.Length || x >= str2Char; x++;)
{
if (str1Char[x] == str2Char[x])
matchCount++;
else
unmatchedCount++;
}
int longestString = str1Char.Length;
if (str2Char.Length > longestString )
longestString = str2Char.Length;
int perc = (matchCount/longestString )*100;
this will fall over if the first string is shorter than the second but you get the jist
来源:https://stackoverflow.com/questions/16840503/how-to-compare-2-strings-and-find-the-difference-in-percentage