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

C#如何比较两个字符串 提取一个开头与另一个结尾的重叠子串

C# 实现字符串首尾重叠公共段匹配

需求说明

查找两个字符串中,一个字符串的末尾段与另一个字符串的开头段完全重合的最长公共部分,示例输入:

string str1 = "CGGCAGTGGTAGTCTGAG";
string str2 = "TGAGCGCGCGCGCGCGCG";
// 预期返回结果:"TGAG"

实现思路

需要覆盖两种匹配场景,取最长匹配结果即可:

  • 第一个字符串的后缀 匹配 第二个字符串的前缀
  • 第二个字符串的后缀 匹配 第一个字符串的前缀
    校验逻辑从最长可能匹配长度(不超过两个字符串的较短长度)开始向下遍历,找到第一个符合要求的匹配段就直接返回,减少不必要的比对;使用Span<char>做字符串切片比对,避免额外的字符串内存分配,提升执行效率。

完整实现代码

using System;

public static class StringOverlapMatcher
{
    /// <summary>
    /// 获取两个字符串中,一个串后缀与另一个串前缀重合的最长公共段
    /// </summary>
    public static string GetLongestOverlap(string strA, string strB)
    {
        // 空值直接返回空
        if (string.IsNullOrEmpty(strA) || string.IsNullOrEmpty(strB))
            return string.Empty;

        // 计算A后缀匹配B前缀的最长长度
        int matchLenA2B = GetSuffixPrefixMatchLength(strA, strB);
        // 计算B后缀匹配A前缀的最长长度
        int matchLenB2A = GetSuffixPrefixMatchLength(strB, strA);

        // 返回更长的匹配结果
        return matchLenA2B >= matchLenB2A
            ? strB.Substring(0, matchLenA2B)
            : strA.Substring(0, matchLenB2A);
    }

    /// <summary>
    /// 计算source的后缀与target的前缀的最长匹配长度
    /// </summary>
    private static int GetSuffixPrefixMatchLength(string source, string target)
    {
        int maxPossibleLen = Math.Min(source.Length, target.Length);
        // 从最长可能长度开始往下找,找到匹配直接返回
        for (int len = maxPossibleLen; len >= 1; len--)
        {
            // 用Span做无分配切片比对
            ReadOnlySpan<char> sourceSuffix = source.AsSpan(source.Length - len, len);
            ReadOnlySpan<char> targetPrefix = target.AsSpan(0, len);
            if (sourceSuffix.SequenceEqual(targetPrefix))
            {
                return len;
            }
        }
        return 0;
    }

    // 测试示例
    public static void Main()
    {
        string str1 = "CGGCAGTGGTAGTCTGAG";
        string str2 = "TGAGCGCGCGCGCGCGCG";
        string result = GetLongestOverlap(str1, str2);
        Console.WriteLine(result); // 输出:TGAG
    }
}

边界场景说明

  • 若两个字符串无任何首尾重合段,返回空字符串
  • 若一个字符串完全是另一个字符串的前缀/后缀(如str1="abc", str2="abcd"),返回较短的那个重合串
  • 若两个方向匹配长度一致,优先返回str1后缀匹配str2前缀的结果
  • 默认大小写敏感,逐字符完全匹配,如需忽略大小写可在比对时增加大小写转换规则

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 14:45:43