You can remove the set of the characters with the help of String.Remove method, but sometime this approach is not preferable by the developers, instead they use the regular expression for it. You can use the Regex.Replace method to strip some characters from the specified string. As shown here:
static string ReplaceString(string strInput) { // Replace invalid characters with empty strings. return System.Text.RegularExpressions.Regex.Replace(strInput, @"[-%$*]", " "); }
In the following code, ReplaceString will replace characters including hyphens(-), percentage (%), doller sign($) and multiply sign (*) from blank space(“ “). You can use the ReplaceString as:
string str = ReplaceString("Welcome-to$ Author%Code*");
However we can change the regular expression according our need. Let’s say that I need to remove all alphanumeric characters except periods (.), at symbols (@), and hyphens (-) then I can use the following pattern of the regular expression:
static string ReplaceString(string strInput) { // Replace invalid characters with empty strings. return System.Text.RegularExpressions.Regex.Replace(strInput, @"[^\w\.@-]"," "); }