Peter Petrov’s Weblog

var me = from practice in programming where practice.IsBestPractice && practice.UseLambda select practice.OptimalPerformance;

Useful method – 7 of N – Ignore case on String.Replace() June 27, 2008

Filed under: .NET Framework,C# — ppetrov @ 3:51 pm
Tags: , , ,

I’ve posted a method to determine if a string contains another string ignoring the case. I’ve also looked all string methods and I’ve found Replace isn’t available in a ignore case variant. I’ve created the missing overload(using an extension methods).

public static string Replace(this string original, string oldValue, string newValue, StringComparison comparisionType)
 {
 if (oldValue == null)
 throw new ArgumentNullException("oldValue");
 if (newValue == null)
 throw new ArgumentNullException("newValue");

 var result = original;

 if (oldValue != newValue)
 {
 int index = -1;
 int lastIndex = 0;

 var buffer = new StringBuilder();

 while ((index = original.IndexOf(oldValue, index + 1, comparisionType)) >= 0)
 {
 buffer.Append(original, lastIndex, index - lastIndex);
 buffer.Append(newValue);

 lastIndex = index + oldValue.Length;
 }
 buffer.Append(original, lastIndex, original.Length - lastIndex);

 result = buffer.ToString();
 }
 return result;
 }

UPDATE : I’ve updated the method to allow newValue to be string.Empty. It will perform like a remove method. WordPress source code posting is broken :(

 

 
Follow

Get every new post delivered to your Inbox.