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");
Rana
  • 4,431
  • 9
  • 32
  • 39
  • 1
    Could you give us an example of what you mean? – Ani Oct 22 '10 at 04:23
  • A good solution is found in this thread by @c-dragon-76 http://stackoverflow.com/questions/244531/is-there-an-alternative-to-string-replace-that-is-case-insensitive – Jaider Aug 10 '12 at 20:32

2 Answers2

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)

Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
  • 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? – Nayan Oct 22 '10 at 05:00
  • 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. – Adriaan Stander Oct 22 '10 at 05:02
  • 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. – Jaider Aug 10 '12 at 20:08
  • 1
    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. – Chad Jun 09 '13 at 00:46
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.

Community
  • 1
  • 1
Garett
  • 16,632
  • 5
  • 55
  • 63