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
1
: 4991 At:- 11/14/2017 1:41:42 PM
C# asp.net c# regex replace special characters with space remove characters from string






2 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);
3
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 = "welcome@to-qa-with-experts#.com";
		string replacestr= Regex.Replace(str, "[^a-zA-Z0-9_]+", " ");
		Console.WriteLine(replacestr);
		Console.ReadLine();
	}
}

Here is the output of it

welcome to qa with experts com

Working Dotnet Fiddle example

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





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

Full Name *

Email *




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