Skip to content

Instantly share code, notes, and snippets.

@andrijac
Last active February 5, 2017 12:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrijac/0f37e53616b76fb8823644ce120524f8 to your computer and use it in GitHub Desktop.
Save andrijac/0f37e53616b76fb8823644ce120524f8 to your computer and use it in GitHub Desktop.
case-insensitive string.Replace C#
//// http://stackoverflow.com/a/244933/84852
public static string ReplaceString(string str, string oldValue, string newValue, StringComparison comparison)
{
if (string.IsNullOrEmpty(oldValue))
{
throw new ArgumentNullException("oldValue");
}
StringBuilder 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();
}
public static class StringExtension
{
public static string Replace(this string str, string oldValue, string newValue, StringComparison comparison)
{
if (string.IsNullOrEmpty(oldValue))
{
throw new ArgumentNullException("oldValue");
}
StringBuilder 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