Remove Special Characters from String using C#

Tag | remove special characters from string c# regex, remove specific characters from string c#, remove all special characters from string c# regex, remove specific characters from a string c#

Remove special characters from string C#.Net

In this article, I will share different ways to remove all spaces and special characters from a string using c#. Find the methods below:-

  • Remove special characters from a string using regex C# ASP.Net
  • Remove special characters from the string using C# Replace()

C# function to remove special characters from string

Find the below source code to remove special characters from the string in asp.net C#:-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Remove all spaces and special characters from string in c#</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h2>How to remove special characters from a string in asp.net c#</h2>
            <table style="width: 80%">
                <tr>
                    <td><b>Remove special characters from string using regex:</b>
                        <br />
                        <asp:Label ID="lblOutput1" runat="server"></asp:Label>
                    </td>
                    <td></td>
                </tr>
                <tr>
                    <td>
                        <br />
                        <b>Remove special characters from string using Replace():</b>
                        <br />
                        <asp:Label ID="lblOutput2" runat="server"></asp:Label>
                    </td>
                    <td></td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>
using System;


public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Remove Special Characters from String using C#
        lblOutput1.Text = RemoveSpecialChar("dotnettec@rk-aspdotnet#string.com");
        lblOutput2.Text = RemoveSpecialCharRegex("dotnettec@rk-aspdotnet#string.com");

    }

    protected string RemoveSpecialCharRegex(string str)
    {
        return str = System.Text.RegularExpressions.Regex.Replace(str, "[^a-zA-Z0-9_]+", " ");
    }

    protected string RemoveSpecialChar(string vInput)
    {
        return vInput.Replace("#", "")
            .Replace("<", "")
            .Replace(">", "")
            .Replace("'", "").Replace("\\", "");
    }
}

Download Source Code

Did you find this post useful? I hope you liked this article. Please share with me your valuable suggestions and feedback.

LEAVE A REPLY

Please enter your comment!
Please enter your name here