Welcome to MSDN Blogs Sign in | Join | Help
C# case insensitve string replace?

private string ReplaceString(string inputStr, string searchStr, string replaceStr, int startIndex)

{

if (inputStr == null || inputStr.Length == 0 || searchStr == null || replaceStr == null || searchStr.Length == 0) return inputStr;

int searchIndex = inputStr.IndexOf(searchStr, startIndex, StringComparison.InvariantCultureIgnoreCase);

if (searchIndex == -1)

return inputStr;

else

return ReplaceString(inputStr.Remove(searchIndex, searchStr.Length).Insert(searchIndex, replaceStr), searchStr, replaceStr, searchIndex + replaceStr.Length);

 

}

Posted: Tuesday, April 28, 2009 9:20 PM by TikiWan

Comments

Tom said:

Don't you think that iteration would be better than recursion for this?

# April 29, 2009 8:57 AM

TikiWan said:

The reason I go for recursion because it is easier to understand and maintain.

If you use live.com to search, you could see that there actually have other faster solution available already. However, they are pretty complicate, it may be useful if you required to use that function frequently. If you only use this function rarely and the project will get touch by multiple developer, usually simple solution is better than complicate solution.

# April 29, 2009 10:03 AM

kanchirk said:

use String.IsNullOrEmpty instead of inputStr == null || inputStr.Length == 0

# May 4, 2009 8:05 AM

TikiWan said:

Yes. I should use String.IsNullOrEmpty instead of checking whether the string by myself.

Old school programmer. ^_^

# May 4, 2009 12:42 PM
New Comments to this post are disabled
Page view tracker