views:

92

answers:

3

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

I need to find and replace a string and ignore the case in c#. What is the best way I can accomplish this? Regex?

+5  A: 

If performance isn't that much of an issue:

//            Input  Find  Replace
Regex.Replace("Jan", "ja", "", RegexOptions.IgnoreCase);

Otherwise, check this article. Fastest alghoritm found there is:

private static string ReplaceEx(string original, 
                    string pattern, string replacement)
{
    int count, position0, position1;
    count = position0 = position1 = 0;
    string upperString = original.ToUpper();
    string upperPattern = pattern.ToUpper();
    int inc = (original.Length/pattern.Length) * 
              (replacement.Length-pattern.Length);
    char [] chars = new char[original.Length + Math.Max(0, inc)];
    while( (position1 = upperString.IndexOf(upperPattern, 
                                      position0)) != -1 )
    {
        for ( int i=position0 ; i < position1 ; ++i )
            chars[count++] = original[i];
        for ( int i=0 ; i < replacement.Length ; ++i )
            chars[count++] = replacement[i];
        position0 = position1+pattern.Length;
    }
    if ( position0 == 0 ) return original;
    for ( int i=position0 ; i < original.Length ; ++i )
        chars[count++] = original[i];
    return new string(chars, 0, count);
}
Jan Jongboom
Remember to use Regex.Escape() on the strings that might contain RegEx special characters.
Chris Taylor
A: 
string stringToReplace = "Some string";
string pattern = "Regex pattern";
string replaceWith = "";

string newString = Regex.Replace(stringToReplace, pattern, replaceWith, RegexOptions.IgnoreCase);
Bernard