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?
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With