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
: 28517 At:- 11/14/2017 1:41:42 PM
C# asp.net 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);

Hope this helps.

4
At:- 11/15/2017 7:44:03 AM Updated at:- 7/26/2022 7:21:37 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


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]+", " ");
		
		Console.WriteLine(UpdatedString);

Output:

Yes Regex Helps alot

remove-special-characters-in-csharp-min.png

Edit:

I would like to add, fastest way to remove special characters in C# is using Linq or StringBuilder and below method

//Linq
public static string RemoveSpecialCharacters(string value)
{
      return new string(value.Select(c => char.IsLetter(c) ? c : ' ').ToArray());
}

//StringBuilder
public static string RemoveSpecialCharactersSB(string str) {
       StringBuilder sb = new StringBuilder();
        foreach (char c in str) {
          if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '.' || c == '_') {
           sb.Append(c);
           }
        }
       return sb.ToString();
    }

Complete sample

        public static void Main()
	{
		string str ="Check# Out!put";
        Console.WriteLine(RemoveSpecialCharacters(str));
	}
	
	public static string RemoveSpecialCharacters(string value)
	{
		return new string(value.Select(c => char.IsLetter(c) ? c : ' ').ToArray());
	}

       public static string RemoveSpecialCharactersSB(string str) {
         StringBuilder sb = new StringBuilder();
         foreach (char c in str) {
          if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '.' || c == '_') {
           sb.Append(c);
           }
        }
        return sb.ToString();
    }

   //output:Check  Out put
1
At:- 3/31/2020 4:00:27 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