Remove specific characters from string C#
14,610
Solution 1
By the power of Regex!
var x = Regex.Replace(tags, @"(\[|""|\])", "");
Solution 2
As alternative, you can use a "simple" Replace
string x = tags.Replace("[","")
.Replace("\"","")
.Replace("]","");
It isn't fast, but it's simple.
If you need more performance you should use an alternative.
please note: that each Replace call returns a new string, and with every call the whole string is reevaluated. Although I often use this myself (due to the readability) it's not recommended for complex patterns or very long string values
Solution 3
Personally, I'd switch your order of operations. For instance
String[] unformattedTags = tags.Split(',');
String[] formattedTags = unformattedTags.Select(itm => itm.Trim( '[','"',']')).ToArray();
This removes the restricted characters from each tag individually.
Related videos on Youtube
Author by
Fawad Bin Tariq
I am Student of BS(Computer Science). In programming languages I am good at C++, JAVA, J2ME, ASP.NET, PHP
Updated on June 04, 2022Comments
-
Fawad Bin Tariq almost 2 years
I have got a string
["foo","bar","buzz"]
from view, i want to remove[
,"
&,]
I have usedstring x = tags.Trim(new Char[] { '[', '"', ']' });
but the output i got isfoo","bar","buzz
instead offoo,bar,buzz
-
Corak over 5 years"creative" approach (not recommended):
new string(tags.ToCharArray().Where(c => !"[\"]".Contains(c)).ToArray());
-
-
Fawad Bin Tariq over 5 yearsI used this but was looking for some better alternative, regex worked for me :)
-
JMadelaine over 5 yearsvar trimmed = Regex.Replace(x, @"([|""|])", ""); Added a second doube quote in the regex due to verbatim string literal. The current answer doesn't compile.
-
FCin over 5 yearsTo me this "simple" approach is 10x better than regex. Deciphering regex is frustrating and here you can clearly see what is going on. It is readable.
-
Corak over 5 yearsAlso,
Trim
acceptsparams
, so you can simply writeString[] formattedTags = tags.Split(',').Select(item => item.Trim('"', '[', ']')).ToArray();
-- no need fornew char[] { ... }
-
Corak over 5 years@A_Name_Does_Not_Matter - that would be nice, but it seems there is no overload of Replace takes
char[]
andstring
. -
A_Sk over 5 yearsYes, there is no overload method... my bad. @Stefan