using System.Text; using GregoryAdam.Base.ExtensionMethods; namespace BaseTest { class test3 { //______________________________________________________________________ static void Main() { Console.WriteLine("{0}", "hello".Replace("o", "123", StringComparison.InvariantCultureIgnoreCase)); Console.ReadLine(); } } }
namespace GregoryAdam.Base.ExtensionMethods { public static partial class ExtensionMethods_String_Replace { //______________________________________________________________________ /// <summary> /// Replaces every occurrence of oldValue with newValue /// </summary> /// <param name="s"></param> /// <param name="oldValue">The string to be replaced</param> /// <param name="newValue">The string that replaces all occurrences of oldValue /// <para>May be null or the empty string</para></param> /// <param name="stringComparison"></param> /// <returns></returns> public static string Replace( this string s, string oldValue, string newValue, StringComparison stringComparison ) { if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(oldValue)) return s; int offset = 0; int n = s.IndexOf(oldValue, offset, stringComparison); if (n < 0 ) return s; int oldLength = oldValue.Length; bool isNewValueNullOrEmpty = string.IsNullOrEmpty(newValue); StringBuilder sb = new StringBuilder(); do { if (n - offset > 0) sb.Append(s, offset, n - offset); if( !isNewValueNullOrEmpty ) sb.Append(newValue); offset = n + oldLength; } while ((n = s.IndexOf(oldValue, offset, stringComparison)) >= 0); if( offset < s.Length ) sb.Append(s, offset, s.Length - offset); return sb.ToString(); } //______________________________________________________________________ } }