You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# 如何在字符串列表中查找与目标字符串最匹配的条目?

C# 字符串最相近匹配实现方案(适用于拼写检查场景)

核心原理

使用*莱文斯坦距离(Levenshtein Distance)*作为相似度判定指标:该算法计算两个字符串互相转换所需的最少单字符操作(插入、删除、替换)次数,数值越小代表字符串相似度越高。

实现代码

using System;
using System.Collections.Generic;
using System.Linq;

public class SpellChecker
{
    // 计算两个字符串的莱文斯坦距离
    private static int GetLevenshteinDistance(string a, string b)
    {
        // 边界处理:其中一个为空时,距离为另一个字符串长度
        if (string.IsNullOrEmpty(a)) return b.Length;
        if (string.IsNullOrEmpty(b)) return a.Length;
        
        // 初始化DP表
        int[,] dp = new int[a.Length + 1, b.Length + 1];
        for (int i = 0; i <= a.Length; i++) dp[i, 0] = i;
        for (int j = 0; j <= b.Length; j++) dp[0, j] = j;
        
        // 填充DP表
        for (int i = 1; i <= a.Length; i++)
        {
            for (int j = 1; j <= b.Length; j++)
            {
                // 当前字符相等时无需操作,否则替换操作成本+1
                int cost = (a[i-1] == b[j-1]) ? 0 : 1;
                dp[i, j] = Math.Min(Math.Min(
                    dp[i - 1, j] + 1, // 删除操作
                    dp[i, j - 1] + 1), // 插入操作
                    dp[i - 1, j - 1] + cost); // 替换操作
            }
        }
        return dp[a.Length, b.Length];
    }

    // 从已知词列表中匹配最相近的词
    public static string FindMostSimilarWord(string source, List<string> knownWords)
    {
        if (knownWords == null || !knownWords.Any()) 
            throw new ArgumentException("已知词列表不能为空");
        
        // 计算每个词的距离,取最小的
        return knownWords
            .Select(word => new { Word = word, Distance = GetLevenshteinDistance(source, word) })
            .OrderBy(item => item.Distance)
            .First()
            .Word;
    }

    // 测试用例
    public static void Main()
    {
        string source = "gnail";
        List<string> KnownWords = new List<string> {
            "orange", 
            "gmail",
            "hotmail",
            "live", 
            "outlook"
        };
        
        string result = FindMostSimilarWord(source, KnownWords);
        Console.WriteLine(result); // 输出:gmail
    }
}

可选优化方案

如果已知词库规模较大,可以提前过滤不符合长度阈值的词汇,减少不必要的距离计算:比如预设允许的最大拼写错误数为2,那么和目标字符串长度差超过2的词汇可以直接跳过,不用参与距离计算。

内容的提问来源于stack exchange,提问作者Mehrez89

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 00:36:04