如何比较2个字符串,并找到百分比的差异? [英] How to compare 2 strings and find the difference in percentage?
本文介绍了如何比较2个字符串,并找到百分比的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是C#的新手。我有2个字符串,它们代表国际语音字母表中的字符。
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
现在我需要比较字符串1 与
字符串2
,并找出多少字符串2
不同于 String 1
。我需要这个值作为百分比值。我如何做到这一点?小代码示例会帮助我很多。您的帮助将非常感谢。
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.
推荐答案
您应该知道您的字符串指标
此外,请查看此如何找到两个字符串之间的区别 - C#问题。
与比较字符串差异时更常见的 Llevenshtein Distance 不同。
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个字符串,并找到百分比的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文