Case Insensitive String Replace

When we do string comparison or string replacement, it’s good practice to compare/replace string ignoring the case of string unless there is a need of it.

It’s very simple when you want to compare two string ignoring the case of string.

for example,

String.Compare(“patel”,”PATEL”,true)

or

string str = “patel”;
str.Equals(“PATEL”,String.Comparison.OrdinalIgnoreCase);

But it’s little bit tricky when you want to replace the string that is case-insensitive.  There is no method available in String class that you can use easily.  There are two ways you can do that.

1) Use RegEx Class

string input = "shailesh patel";
string pattern = "Shailesh";
string replacement = "shail";

string newString = Regex.Replace(input,pattern,replacement,RegexOptions.IgnoreCase);

2) Create your custom method to do case insensitive  string replacement

public static string ReplaceString(string OldString, string stringToBeReplaced, string newString, bool CaseInsensitive)
{

int index = 0;

if (CaseInsensitive)
  OldString.IndexOf(stringToBeReplaced,0,     StringComparison.OrdinalIgnoreCase);
else
  index = OldString.IndexOf(stringToBeReplaced, 0);

if (index == -1)
   return OldString;

OldString = OldString.Substring(0, index) + newString + OldString.Substring(index + stringToBeReplaced.Length);

return OldString;
}
Hope this helps you.
Posted in Microsoft Technology Tagged with: ,

Ads