C# 在字符串列表中查找与输入字符串最接近的匹配项

C# 在字符串列表中查找与输入字符串最接近的匹配项,c#,.net,vb.net,visual-studio-2012,C#,.net,Vb.net,Visual Studio 2012,我在为.net查找最接近匹配字符串的实现时遇到问题 我想匹配字符串列表,例如: 输入字符串:“Publiczna Szkoła Podstawowa im.Bolesława Chrobrego wąsoszu” 字符串列表: Publiczna Szkoła Podstawowa im。B.Chrobrego wąsoszu Szkoła Podstawowa Specjalna 我是亨利卡·辛基维察·沃索苏(Henryka Sienkiewicza wąsoszu) Szkoła Podst

我在为.net查找最接近匹配字符串的实现时遇到问题

我想匹配字符串列表,例如:

输入字符串:“Publiczna Szkoła Podstawowa im.Bolesława Chrobrego wąsoszu”

字符串列表:

Publiczna Szkoła Podstawowa im。B.Chrobrego wąsoszu

Szkoła Podstawowa Specjalna

我是亨利卡·辛基维察·沃索苏(Henryka Sienkiewicza wąsoszu)

Szkoła Podstawowa im。罗穆阿尔达·特劳格塔·沃索苏·戈尼姆

这显然需要与“Publiczna Szkoła Podstawowa im.B.Chrobrego wąsoszu”相匹配

有哪些算法可用于.net?

编辑距离是一种量化两个字符串的不同程度的方法 (例如,单词)通过计算最小数量的 将一个字符串转换为另一个字符串所需的操作

非正式地说,两个单词之间的Levenshtein距离是最小的 单字符编辑次数(即插入、删除或删除) 替换)将一个单词转换为另一个单词所需的

使用系统;
/// 
///包含近似字符串匹配
/// 
静态类levenshteindication
{
/// 
///计算两个字符串之间的距离。
/// 
公共静态整数计算(字符串s、字符串t)
{
int n=s.长度;
int m=t.长度;
int[,]d=新的int[n+1,m+1];
//第一步
如果(n==0)
{
返回m;
}
如果(m==0)
{
返回n;
}
//步骤2

对于(int i=0;i).NET不提供任何现成的功能-您需要自己实现一个算法。例如,您可以使用,如下所示:

// This code is an implementation of the pseudocode from the Wikipedia,
// showing a naive implementation.
// You should research an algorithm with better space complexity.
public static int LevenshteinDistance(string s, string t) {
    int n = s.Length;
    int m = t.Length;
    int[,] d = new int[n + 1, m + 1];
    if (n == 0) {
        return m;
    }
    if (m == 0) {
        return n;
    }
    for (int i = 0; i <= n; d[i, 0] = i++)
        ;
    for (int j = 0; j <= m; d[0, j] = j++)
       ;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
            d[i, j] = Math.Min(
                Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
                d[i - 1, j - 1] + cost);
        }
    }
    return d[n, m];
}
//此代码是来自Wikipedia的伪代码的实现,
//显示一个幼稚的实现。
//你应该研究一种空间复杂度更好的算法。
公共静态int-levenshteindication(字符串s、字符串t){
int n=s.长度;
int m=t.长度;
int[,]d=新的int[n+1,m+1];
如果(n==0){
返回m;
}
如果(m==0){
返回n;
}

对于(int i=0;i非常快!您的代码的结果与我的实现进行了100%的验证,但您的代码的运行速度比我提出的速度快2倍。
// This code is an implementation of the pseudocode from the Wikipedia,
// showing a naive implementation.
// You should research an algorithm with better space complexity.
public static int LevenshteinDistance(string s, string t) {
    int n = s.Length;
    int m = t.Length;
    int[,] d = new int[n + 1, m + 1];
    if (n == 0) {
        return m;
    }
    if (m == 0) {
        return n;
    }
    for (int i = 0; i <= n; d[i, 0] = i++)
        ;
    for (int j = 0; j <= m; d[0, j] = j++)
       ;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
            d[i, j] = Math.Min(
                Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
                d[i - 1, j - 1] + cost);
        }
    }
    return d[n, m];
}