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 个字符串并找出百分比差异?
基础教程推荐
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
