Last active
September 14, 2015 14:07
-
-
Save poulfoged/0d1fb0f377fd77ca3de1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal static class StringExtensions | |
{ | |
public static string ReplaceCaseInsensitive(this string source, object replacements) | |
{ | |
replacements | |
.GetType() | |
.GetProperties() | |
.Select(p => new {p.Name, Value = p.GetValue(replacements) as string ?? ""}) | |
.ToList() | |
.ForEach(p => { source = ReplaceCaseInsensitive(source, string.Format("{{{0}}}", p.Name), p.Value); }); | |
return source; | |
} | |
private static string ReplaceCaseInsensitive(string originalString, string oldValue, string newValue) | |
{ | |
var startIndex = 0; | |
while (true) | |
{ | |
startIndex = originalString.IndexOf(oldValue, startIndex, StringComparison.InvariantCultureIgnoreCase); | |
if (startIndex == -1) | |
break; | |
originalString = originalString.Substring(0, startIndex) + newValue + originalString.Substring(startIndex + oldValue.Length); | |
startIndex += newValue.Length; | |
} | |
return originalString; | |
} | |
} | |
[TestFixture] | |
public class StringExtensionTests | |
{ | |
[Test] | |
public void Can_perform_basic_replace() | |
{ | |
////Act | |
var result = "{test}".ReplaceCaseInsensitive(new {Test = "dimmer"}); | |
////Assert | |
Assert.That(result, Is.EqualTo("dimmer")); | |
} | |
[Test] | |
public void Can_perform_double_replace() | |
{ | |
////Act | |
var result = "{test}{test2}".ReplaceCaseInsensitive(new { Test = "dimmer", Test2 = "dimmer2" }); | |
////Assert | |
Assert.That(result, Is.EqualTo("dimmerdimmer2")); | |
} | |
[Test] | |
public void Null_value_is_ok() | |
{ | |
////Act | |
var result = "{test}{test2}".ReplaceCaseInsensitive(new { Test = "dimmer", Test2 = (string)null }); | |
////Assert | |
Assert.That(result, Is.EqualTo("dimmer")); | |
} | |
[Test] | |
public void Null_source_is_ok() | |
{ | |
////Act | |
var result = "".ReplaceCaseInsensitive(new { Test = "dimmer", Test2 = (string)null }); | |
////Assert | |
Assert.That(result, Is.EqualTo("")); | |
} | |
[Test] | |
public void Case_is_ignored() | |
{ | |
////Act | |
var result = "{tesT}".ReplaceCaseInsensitive(new { Test = "dimmer" }); | |
////Assert | |
Assert.That(result, Is.EqualTo("dimmer")); | |
} | |
[Test] | |
public void Non_existent_is_ignored() | |
{ | |
////Act | |
var result = "nothing".ReplaceCaseInsensitive(new { Test = "dimmer" }); | |
////Assert | |
Assert.That(result, Is.EqualTo("nothing")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment