Case-Insensitive String.Replace in C# and VB.NET

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));
		stringBuilder.Append(replace);
		currIndex += search.Length;
		lastIndex = currIndex;
		currIndex = input.IndexOf(search, currIndex, comparison);
	}
	stringBuilder.Append(input.Substring(lastIndex));
	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))
		stringBuilder.Append(replace)
		currIndex += search.Length
		lastIndex = currIndex
		currIndex = input.IndexOf(search, currIndex, comparison)
	End While
	stringBuilder.Append(input.Substring(lastIndex))
	Return stringBuilder.ToString()
End Function

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

Leave a Reply