Original: Replacefirst and Replacelast of C # implementations
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); Note: If you replace the old value with a special symbol, the substitution will fail and the workaround such as the special symbol is "(": To add Oldvalue=oldvalue.replace before calling this method ("(", ""//(");
Replacelast:
Public static string Replacelast (string input, String oldValue, string newvalue) {int index = in Put. 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 (); } }
C # Implementation of Replacefirst and Replacelast