How to remove or replace all special characters from a string in C#?

I want to send an XML data to server, and to make the XML valid i have to remove all the special characters(@,#,%..) etc from the string of address and send it to server , as it accpets XML data without it, otherwise it throws error

So how can remove special characters from string using C# in ASP.NET?

Suppose my String has

Suite #218

So it must return

Suite 218

to make it work

Any help is appreciated, thanks

Asked by:- jaya
: 13397 At:- 11/14/2017 1:41:42 PM
C# c# regex replace special characters with space remove characters from string

3 Answers
profileImage Answered by:- pika

You can replace characters in C# using the Regular expressions

using System.Text.RegularExpressions;

var StringToBeRepalced="Suite #218";

var StringWithoutSpclCharac= Regex.Replace(StringToBeRepalced, @"[^0-9a-zA-Z\._]", "");

//Output StringWithoutSpclCharac = Suite 218

Although above method is quite efficient you can still add a method for it in another way like below

public static string RemoveSpecialChars(string str)
            // Create  a string array and add the special characters you want to remove
            string[] chars = new string[] { ",", ".", "/", "!", "@", "#", "$", "%", "^", "&", "*", "'", "\"", ";", "_", "(", ")", ":", "|", "[", "]" };
            //Iterate the number of times based on the String array length.
            for (int i = 0; i < chars.Length; i++)
                if (str.Contains(chars[i]))
                    str = str.Replace(chars[i], "");
            return str;

And can call the above method like

string str = "Suite #208";
string ReturnedString=RemoveSpecialChars(str);
At:- 11/15/2017 7:44:03 AM
Commenting it late but thanks you for your well-explained answer, Method 1 works for me, didn't tried method 2 0
By : jaya - at :- 2/3/2018 8:03:24 AM

profileImage Answered by:- jaiprakash

I have found this another simple solution which may help to remove special characters easily using C#

using System;
using System.Text.RegularExpressions;

public class Program
    public static void Main(string[] args)
		string str = "";
		string replacestr= Regex.Replace(str, "[^a-zA-Z0-9_]+", " ");

Here is the output of it

welcome to qa with experts com

Working Dotnet Fiddle example

At:- 10/2/2018 3:30:35 PM

profileImage Answered by:- vikas_jk

Another method to replace all special chaarcters in C# using Regular expression (Regex)

        string MainString = "Yes@Regex&Helps(alot)";
		//replace special characters with space
        string UpdatedString =  Regex.Replace(MainString, @"[^0-9a-zA-Z]+", " ");


Yes Regex Helps alot


At:- 3/31/2020 4:00:27 PM

Login/Register to answer
Register directly by posting answer/details

Full Name *

Email *

By posting your answer you agree on privacy policy & terms of use

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly