如何比较两个字符串

如何比较两个字符串

本文介绍了如何比较两个字符串,找到百分比的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的C#。我有两个字符串,它们是从国际音标重新presenting字符。

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 不同串1 。我需要这个值作为一个百分比值。我怎样才能做到这一点?小code例子会帮助我很多。您的帮助将大大AP preciated。

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.

推荐答案

您应该知道什么是你的字符串公制

You should have tell what is your String Metric

此外,在这如何找到两个字符串之间的区别 - C#的问题。

这将炭炭相比较,它比 Llevenshtein距离这是比较常见的,当不同比较字符串的差异。

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;
}

这篇关于如何比较两个字符串,找到百分比的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 10:03