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());

}