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

C#如何高效替换字符串中指定子串的最后一次出现内容

优化实现方案

原实现存在的问题

  • 调用Split生成字符串数组会产生额外的内存开销,长字符串场景下效率低
  • 全局调用Replace会替换所有和最后一段内容匹配的子串,如果路径前面出现相同内容会被误修改,不符合「仅替换最后一次出现的指定值」的需求

最优实现思路

直接使用.NET内置的LastIndexOf方法定位目标子串最后一次出现的位置,再通过字符串裁剪拼接完成替换,全程没有多余的中间对象生成,逻辑简洁高效。

代码示例

场景直接实现

using System;  

namespace StringReplaceSample  
{  
    public class Program  
    {
        public static void Main(string[] args)  
        {
            string example = "https://something/ABCD/EFGH/IJKL/ABCD?id=1234567910";
            const string OLD_STR = "ABCD";
            const string NEW_STR = "NEW";

            // 查找目标字符串最后一次出现的下标
            int lastIndex = example.LastIndexOf(OLD_STR);
            string result = lastIndex < 0
                // 未找到匹配内容直接返回原字符串
                ? example
                // 移除对应位置的旧字符串,插入新字符串
                : example.Remove(lastIndex, OLD_STR.Length).Insert(lastIndex, NEW_STR);
            
            Console.WriteLine("Original string:" + example);
            Console.WriteLine("Trimmed string:" + result); 
        }  
    }  
}

可复用扩展方法封装

如果需要频繁使用这个能力,可以封装为字符串扩展方法,调用更简洁:

public static class StringExtension
{
    public static string ReplaceLast(this string source, string oldValue, string newValue)
    {
        if (string.IsNullOrEmpty(source) || string.IsNullOrEmpty(oldValue)) 
            return source;
        
        int lastPos = source.LastIndexOf(oldValue);
        return lastPos < 0 
            ? source 
            : source.Remove(lastPos, oldValue.Length).Insert(lastPos, newValue);
    }
}

// 调用示例
// var result = example.ReplaceLast("ABCD", "NEW");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:24:10