Search This Blog

Tuesday 1 September 2015

Remove special characters from string c# or Eliminate special characters from string c# or Remove special characters from string c# asp.net

Step 1:- Method

protected string EliminateSpecialChars(string str)
        {
            string[] chars = { "\"""\\""/"":""*""?""<"">""|""\r""\n"" "};

            foreach (string t in chars)
            {
                if (str.Contains(t))
                {
                    str = str.Replace(t, "").Trim();
                }
            }
            return str;
        }

Step 2:- EliminateSpecialCharacters.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EliminateSpecialCharacters.aspx.cs" Inherits="Demo.EliminateSpecialCharacters" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
    </div>
    </form>
</body>
</html>

Step 2:- EliminateSpecialCharacters.aspx.cs

using System;
using System.Web.UI;

namespace Demo
{
    public partial class EliminateSpecialCharacters : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string strValue = EliminateSpecialChars("abcde\\fgh?ijk*lmnop qrst|uvwxyz");
            Response.Write(strValue);
        }

        protected string EliminateSpecialChars(string str)
        {
            string[] chars = { "\"""\\""/"":""*""?""<"">""|""\r""\n"" "};

            foreach (string t in chars)
            {
                if (str.Contains(t))
                {
                    str = str.Replace(t, "").Trim();
                }
            }
            return str;
        }
    }
}

Step 3:- Output

abcdefghijklmnopqrstuvwxyz 


Note:

If your string containing any other character, you can add those also in a string array.

Example:

If a string containing ‘,’ comma so you can add the comma in a string array.

So, after adding string array looks like this 

string[] chars = { "\"""\\""/"":""*""?""<"">""|""\r""\n"" ""," };

No comments:

Post a Comment