Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace the string of special characters in C#

Tags:

My requirement is:

I have to replace some special characters like * ' " , _ & # ^ @ with string.Empty, and I have to replace blank spaces with -.

This is my code:

 Charseparated = Charseparated
    .Replace("*","")
    .Replace("'","")
    .Replace("&","")
    .Replace("@","") ...

For so many characters to replace I have to use as many as Replace's which I want to avoid.

Is there another efficient way to remove the special characters, but at the same time replace blank spaces with -?

like image 481
Venkat Avatar asked Jun 23 '17 07:06

Venkat


People also ask

How do you replace special characters in regex?

If you are having a string with special characters and want's to remove/replace them then you can use regex for that. Use this code: Regex. Replace(your String, @"[^0-9a-zA-Z]+", "")

How do you handle special characters in C#?

C# includes escaping character \ (backslash) before these special characters to include in a string. Use backslash \ before double quotes and some special characters such as \,\n,\r,\t, etc. to include it in a string.


1 Answers

I believe, best is to use a regular expression here as below

s/[*'",_&#^@]/ /g

You can use Regex class for this purpose

Regex reg = new Regex("[*'\",_&#^@]");
str1 = reg.Replace(str1, string.Empty);

Regex reg1 = new Regex("[ ]");
str1 = reg.Replace(str1, "-");
like image 145
Rahul Avatar answered Oct 10 '22 12:10

Rahul