且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#实现的ReplaceFirst和ReplaceLast

更新时间:2022-10-04 17:33:19

原文: C#实现的ReplaceFirst和ReplaceLast

ReplaceFirst:

                     public static string ReplaceFirst(string input, string oldValue, string newValue) { Regex regEx = new Regex(oldValue, RegexOptions.Multiline); return regEx.Replace(input, newValue==null?"":newValue, 1); } 注意:如果替换的旧值中有特殊符号,替换将会失败,解决办法 例如特殊符号是“(”: 要在调用本方法前加oldValue=oldValue.Replace("(","//(");

 

ReplaceLast:

                    public static string ReplaceLast(string input, string oldValue, string newValue) { int index = input.LastIndexOf(oldValue); if (index < 0) { return input; } else { StringBuilder sb = new StringBuilder(input.Length - oldValue.Length + newValue.Length); sb.Append(input.Substring(0, index)); sb.Append(newValue); sb.Append(input.Substring(index + oldValue.Length, input.Length - index - oldValue.Length)); return sb.ToString(); } }