Last active
February 5, 2017 12:31
-
-
Save andrijac/0f37e53616b76fb8823644ce120524f8 to your computer and use it in GitHub Desktop.
case-insensitive string.Replace C#
This file contains 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
//// 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(); | |
} |
This file contains 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
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