我是C#的新手。我有2个字符串,它们代表国际音标字符。
String 1 - ðə ɻɛd fɑks ɪz hʌŋgɻi
String 2 - ðæt ɪt foks ɪn ðʌ sʌn ɻe͡i
现在我需要将String 1
与String 2
进行比较,并找出String 2
与String 1
的差异。我需要这个值作为百分比值。我怎样才能做到这一点?小代码示例将帮助我很多。对你的帮助表示感谢。
答案 0 :(得分:7)
你应该知道你的String Metric
是什么另外,请查看此How to find difference between two strings - C#问题。
这将比较字符char,它与Llevenshtein Distance不同,这在比较字符串差异时更常见。
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;
}
答案 1 :(得分:0)
的内容
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;
如果第一个字符串比第二个字符串短但你得到了jist
,这将会失败