Поделиться через


SYSK 322: RemoveChars Function For Your Utilities Assembly

Can you think of a case where you’d like to remove more than one character from a string? Some examples include '\r' and '\n' as a carriage return + line feed, or '$', ',' and ' ' for currency data entry fields…

 

Of course you could call string.Replace as many times as there are number of characters you want to strip out… or, you could use the function below to do the job.

 

public static string RemoveChars(string text, char[] removeChars)

{

    List<char> result = new List<char>();

   

    foreach(char c in text.ToCharArray())

    {

        bool remove = false;

        foreach (char ic in removeChars)

        {

            if (c == ic)

            {

                remove = true;

    break;

            }

        }

        if (remove == false)

            result.Add(c);

    }

    return new string(result.ToArray());

}

Comments

  • Anonymous
    April 05, 2007
    The comment has been removed

  • Anonymous
    April 06, 2007
    Is this faster than just using String.Replace()?  

  • Anonymous
    April 10, 2007
    String.Replace() is O(n), you would have to call it removeChars.Length times. Plus you cannot call String.Replace(char, ''), you'd have to ToString each char being passed. Plus there are the intermediate strings being created. Odds are the speed should be abysmal. However, in practice for small numbers of replacement characters, foreach using String.Replace() is really fast, much faster than any of the methods Irene or I have shown. However, once the number of characters you need to replace increases, slowly our methods overtake a naive String.Replace(). Remember, it is important to get the functionality correct first, and then optimize the method for your application later.