Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: get rid of multiple invalid characters in string [duplicate]

I am new to C#. Say that I have a string like this:

string test = 'yes/, I~ know# there@ are% invalid£ characters$ in& this* string^";

If I wanted to get rid of a single invalid symbol, I would do:

if (test.Contains('/')) 
{ 
    test = test.Replace("/","");
} 

But is there a way I can use a list of symbols as argument of the Contains and Replace functions, instead of deleting symbols one by one?

like image 976
Zizzipupp Avatar asked Dec 06 '22 09:12

Zizzipupp


2 Answers

I would go with the regular expression solution

string test = Regex.Replace(test, @"\/|~|#|@|%|£|\$|&|\*|\^", "");

Add a | or parameter for each character and use the replace

Bear in mind the \/ means / but you need to escape the character.

like image 155
Athanasios Kataras Avatar answered Dec 29 '22 13:12

Athanasios Kataras


You'll likely be better off defining acceptable characters than trying to think of and code for everything you need to eliminate.

Because you mention that you are learning, sounds like the perfect time to learn about Regular Expressions. Here are a couple of links to get you started:

  • Regular Expression Language - Quick Reference (MSDN)
  • C# Regex.Match Examples (DotNetPerls
like image 35
Roger Oney Avatar answered Dec 29 '22 14:12

Roger Oney