Case Insensitive String Replace

While working with C#, I've come to find that the Replace() method does not have an option to perform a case insensitive search. This seems a little weird, but then again I've found it best not to try and figure Microsoft out. Regardless, after that, I started messing with RegEx thinking that might solve the problem. While I'm sure it can, I have yet to figure out how.

Basically, I am cycling through a Hashtable, and want to search a string (sBuffer) with the Hashtable key (sFind). If found, it replaces it with the Hashtable value (sReplace).

Any suggestions?

Thora_FanAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
eternal_21Connect With a Mentor Commented:
Regex saves the day again!  Does this do the trick, Thora_Fan?

  string ReplaceString(string sBuffer, string sFind, string sReplace)
  {
    string regexString = "";
    foreach(char c in sFind)
      regexString += "[" + c.ToString().ToLower() + c.ToString().ToUpper() + "]";
    return System.Text.RegularExpressions.Regex.Replace(sBuffer, regexString, sReplace);
  }
0
 
simion_tishlerCommented:
You could convert both to upper case before using replace. Is this too simple an answer.

Or alternatively you could write your own search and replace algorithm. I know a good one if your interested.
0
 
eternal_21Commented:
Ooooh simion, you snuck that one just ahead of me!
0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
simion_tishlerCommented:
Yeah well I need some points to give people for helping me. So I thought I'd try and help with some answers.
0
 
Thora_FanAuthor Commented:
Thank you both for answering. That did the trick indeed, eternal_21. Thanks a lot.
0
 
eternal_21Commented:
Hey Simion, came across this and thought I would pass it on to you:

  string ReplaceString(string sBuffer, string sFind, string sReplace)
  {
    return System.Text.RegularExpressions.Regex.Replace(sBuffer, sFind, sReplace, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  }

Nice option, eh?
0
 
simion_tishlerCommented:
Yeah well

after all that Microsoft wasn't as stupid as we thought.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.