Created
February 12, 2014 17:06
-
-
Save csharpforevermore/8959866 to your computer and use it in GitHub Desktop.
Like String.Replace but can do so with regards to case and culture.
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
using System; | |
using System.Text; | |
public static class ExtensionMethods | |
{ | |
/// <summary> | |
/// Case insensitive string replacement | |
/// </summary> | |
/// <param name="str">string to process</param> | |
/// <param name="oldValue">old value to find</param> | |
/// <param name="newValue">new value to replace</param> | |
/// <param name="comparison">Case sensitive / insensitive</param> | |
/// <returns>A string with the value replaced - case insensitively</returns> | |
public static string ReplaceString(this string str, string oldValue, string newValue, StringComparison comparison) | |
{ | |
var sb = new StringBuilder(); | |
int previousIndex = 0; | |
int index = str.IndexOf(oldValue, comparison); | |
while (index != -1) | |
{ | |
sb.Append(str.Substring(previousIndex, index - previousIndex)); | |
sb.Append(newValue); | |
index += oldValue.Length; | |
previousIndex = index; | |
index = str.IndexOf(oldValue, index, comparison); | |
} | |
sb.Append(str.Substring(previousIndex)); | |
return sb.ToString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment