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

标签 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

Szkoła Podstawowa im.Henryka Sienkiewicza 和 Wąsoszu

Szkoła Podstawowa im。 Romualda Traugutta wąsoszu Górnym

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

.net 有哪些可用的算法?

最佳答案

Edit distance

Edit distance is a way of quantifying how dissimilar two strings (e.g., words) are to one another by counting the minimum number of operations required to transform one string into the other.

Levenshtein distance

Informally, the Levenshtein distance between two words is the minimum number of single-character edits (i.e. insertions, deletions or substitutions) required to change one word into the other.

Fast, memory efficient Levenshtein algorithm

C# Levenshtein

using System;

/// <summary>
/// Contains approximate string matching
/// </summary>
static class LevenshteinDistance
{
    /// <summary>
    /// Compute the distance between two strings.
    /// </summary>
    public static int Compute(string s, string t)
    {
    int n = s.Length;
    int m = t.Length;
    int[,] d = new int[n + 1, m + 1];

    // Step 1
    if (n == 0)
    {
        return m;
    }

    if (m == 0)
    {
        return n;
    }

    // Step 2
    for (int i = 0; i <= n; d[i, 0] = i++)
    {
    }

    for (int j = 0; j <= m; d[0, j] = j++)
    {
    }

    // Step 3
    for (int i = 1; i <= n; i++)
    {
        //Step 4
        for (int j = 1; j <= m; j++)
        {
        // Step 5
        int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;

        // Step 6
        d[i, j] = Math.Min(
            Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
            d[i - 1, j - 1] + cost);
        }
    }
    // Step 7
    return d[n, m];
    }
}

class Program
{
    static void Main()
    {
    Console.WriteLine(LevenshteinDistance.Compute("aunt", "ant"));
    Console.WriteLine(LevenshteinDistance.Compute("Sam", "Samantha"));
    Console.WriteLine(LevenshteinDistance.Compute("flomax", "volmax"));
    }
}

关于c# - 在字符串列表中查找与输入字符串最接近的匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13793560/

相关文章:

c# - Object.GetType 也可以用于后期绑定(bind)吗?

css - 为什么我在这个 vb.net asp :repeater no matter what i do on rgroups itembound 中找不到控件 txt

c# - 在属性网格中扩展自定义对象而不对类进行任何修改?

c# - 可访问性不一致 : field type 'world' is less accessible than field 'frmSplashScreen

c# - 如何将EF数据库恢复为默认值?

c# - 如何创建包含 IPv4 地址的文本框?

c# - 使用无效的 SSL 证书从 WSDL 生成服务代理时出现问题

c# - 对客户的 SQL Server 数据库更改

c# - System.IO.FileShare 有限制吗?

c++ - 帮助希望编写 vb 代码的新人