Skip to content

Instantly share code, notes, and snippets.

@csharpforevermore
Created February 12, 2014 17:06
Show Gist options
  • Save csharpforevermore/8959866 to your computer and use it in GitHub Desktop.
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.
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