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
现在我需要比较 String 1
与 String 2
并找出 String 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# 问题.
Also, have a look in this How to find difference between two strings - C# question.
这将逐个字符比较,它不同于更常见的 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 个字符串并找出百分比差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何比较 2 个字符串并找出百分比差异?
基础教程推荐
- MS Visual Studio .NET 的替代品 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01