Here you can find a Case-Insensitive String.Replace method for C# and VB.NET.

Sample C#

public static string ReplaceWithStringComparison(string input, string search, string replace, StringComparison comparison)
	var stringBuilder = new StringBuilder();
	var lastIndex = 0;
	var currIndex = input.IndexOf(search, comparison);
	while (currIndex != -1)
		stringBuilder.Append(input.Substring(lastIndex, currIndex - lastIndex));
		currIndex += search.Length;
		lastIndex = currIndex;
		currIndex = input.IndexOf(search, currIndex, comparison);
	return stringBuilder.ToString();

Sample VB.NET

Public Shared Function ReplaceWithStringComparison(input As String, search As String, replace As String, comparison As StringComparison) As String
	Dim stringBuilder = New StringBuilder()
	Dim lastIndex = 0
	Dim currIndex = input.IndexOf(search, comparison)
	While currIndex <> -1
		stringBuilder.Append(input.Substring(lastIndex, currIndex - lastIndex))
		currIndex += search.Length
		lastIndex = currIndex
		currIndex = input.IndexOf(search, currIndex, comparison)
	End While
	Return stringBuilder.ToString()
End Function

3 thought on “Case-Insensitive String.Replace in C# and VB.NET”

Leave a Reply