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

如何提取List<string>中字符串的公共前缀与差异后缀并按指定格式拼接

C# 字符串集合拼接为公共前缀+反斜杠分隔后缀实现方案

核心实现代码

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

class StringCombineDemo
{
    static void Main()
    {
        List<string> myList = new List<string>() 
        {
            "AS2258B43C014AI9954803",
            "AS2258B43C014AI9954603",
            "AS2258B43C014AI9954703",
            "AS2258B43C014AI9954503",
            "AS2258B43C014AI9954403",
            "AS2258B43C014AI9954203",
            "AS2258B43C014AI9954303",
            "AS2258B43C014AI9954103",
        };

        // 空集合直接返回空
        if (!myList.Any())
        {
            Console.WriteLine(string.Empty);
            return;
        }

        // 计算最长公共前缀长度
        int minStrLength = myList.Min(s => s.Length);
        int commonPrefixLen = 0;
        while (commonPrefixLen < minStrLength)
        {
            char currentCheckChar = myList[0][commonPrefixLen];
            if (myList.All(str => str[commonPrefixLen] == currentCheckChar))
            {
                commonPrefixLen++;
            }
            else
            {
                break;
            }
        }

        // 提取所有字符串的差异后缀
        List<string> suffixList = myList.Select(str => str.Substring(commonPrefixLen)).ToList();

        // 按要求格式拼接结果
        string result = $"{myList[0].Substring(0, commonPrefixLen)}{suffixList[0]}\\{string.Join("\\", suffixList.Skip(1))}";

        Console.WriteLine(result);
    }
}

逻辑说明

  • 先做边界校验,避免空集合操作抛出异常
  • 计算公共前缀时,先取所有字符串的最小长度避免索引越界,逐位对比所有字符串相同位置的字符,直到出现不一致的字符为止,得到公共前缀的总长度
  • 提取每个字符串去掉公共前缀后的差异后缀部分
  • 拼接规则为:公共前缀 + 第一个字符串的后缀(即第一个完整字符串),剩余后缀直接用反斜杠拼接在后面

优化提示

如果你的业务场景中所有字符串长度固定,差异后缀的长度固定(比如本例中后缀都是3位),可以直接跳过公共前缀计算步骤,硬编码公共前缀长度为字符串总长度 - 后缀长度,运行效率更高。

运行上述代码输出结果和要求的示例完全一致:AS2258B43C014AI9954803\603\703\503\403\203\303\103


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 03:24:03