如何比较 2 个字符串并找出百分比差异?

How to compare 2 strings and find the difference in percentage?(如何比较 2 个字符串并找出百分比差异?)
本文介绍了如何比较 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 1String 2 并找出 String 2String 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 个字符串并找出百分比差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)