6

Is there a way to do case insensitive replace on a string without using regular expression in C#?

something like this

string x = "Hello";

x = x.Replace("hello", "hello world");
2
  • 1
    Could you give us an example of what you mean? Commented Oct 22, 2010 at 4:23
  • A good solution is found in this thread by @c-dragon-76 stackoverflow.com/questions/244531/… Commented Aug 10, 2012 at 20:32

2 Answers 2

5

You can try something like

string str = "Hello";
string replace = "hello";
string replaceWith = "hello world";
int i = str.IndexOf(replace, StringComparison.OrdinalIgnoreCase);
int len = replace.Length;
str = str.Replace(str.Substring(i, len), replaceWith);

Have a look at String.IndexOf Method (String, StringComparison)

Sign up to request clarification or add additional context in comments.

4 Comments

I doubt that Replace will be able to replace the string. Its a different matter that you got index by ignoring the case. Is it a tested example?
Yes, I have tested this. Just remember that I am retrieving the start index based on the search string, but replacing based on the sub string from the original string, so it will match.
it doesn't work as we would expected in other situations... e.g. if str = "Hello-Hello" it will return "hello world-hello world" but it's str="Hello-hello" it will return "hello world-hello"... this partial solution need to be redesign.
That only replaces the first occurrence, not all. If you where to put it in a loop and make it an extension method, that would be cool.
1

The following links may be of help.

Is there an alternative to string.Replace that is case-insensitive?

http://www.codeproject.com/KB/string/fastestcscaseinsstringrep.aspx

http://www.west-wind.com/weblog/posts/60355.aspx

There is also the Strings.Replace function in the Microsoft.VisualBasic assembly.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.