vote buttons
1
04 Dec 2015 by K Bonneau

Case Insensitive String.Replace Extension Method

Contract
GlobalExtensionMethods
public static string Replace( this string source, string oldValue, string newValue, StringComparison comparisonType);
Test Cases
vote buttons
1
Created By K Bonneau
public void Replaces_WhenCaseMatches() { var source = "I want to replace THIS with THAT."; var expected = "I want to replace THAT with THAT."; Assert.AreEqual(expected, source.Replace("THIS","THAT", StringComparison.CurrentCulture)); }
vote buttons
1
Created By K Bonneau
public void Replaces_WhenCaseDoesNotMatchAndStringComparisonIsCaseInSensitive() { var source = "I want to replace THIS with THAT."; var expected = "I want to replace THAT with THAT."; Assert.AreEqual(expected, source.Replace("this","THAT", StringComparison.OrdinalIgnoreCase)); }
vote buttons
1
Created By K Bonneau
using System.Globalization; public void WorksForOtherCultures() { Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR"); var source = "I want to replace THIS with THAT."; var expected = "I want to replace THAT with THAT."; Assert.AreEqual(expected, source.Replace("this", "THAT", StringComparison.OrdinalIgnoreCase)); }
vote buttons
1
Created By K Bonneau
public void DoesNotReplace_WhenCaseDoesNotMatchAndStringComparisonIsCaseSensitive() { var source = "I want to replace THIS with THAT."; var expected = "I want to replace THIS with THAT."; Assert.AreEqual(expected, source.Replace("this","THAT", StringComparison.CurrentCulture)); }
You must be logged in to add test cases

1 Solution

vote buttons
1
04 Dec 2015 by K Bonneau
public static class GlobalExtensionMethods { public static string Replace( this string source, string oldValue, string newValue, StringComparison comparisonType) { StringBuilder sb = new StringBuilder(); int previousIndex = 0; int index = source.IndexOf(oldValue, comparisonType); while (index != -1) { sb.Append(source.Substring(previousIndex, index - previousIndex)); sb.Append(newValue); index += oldValue.Length; previousIndex = index; index = source.IndexOf(oldValue, index, comparisonType); } sb.Append(source.Substring(previousIndex)); return sb.ToString(); } }
Test Case Run Summary
Replaces_WhenCaseMatches
Replaces_WhenCaseDoesNotMatchAndStringComparisonIsCaseInSensitive
WorksForOtherCultures
DoesNotReplace_WhenCaseDoesNotMatchAndStringComparisonIsCaseSensitive
download solution
Try this Solution
Comments