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.

Share:
14,610

Related videos on Youtube

Fawad Bin Tariq
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, 2022

Comments

  • Fawad Bin Tariq
    Fawad Bin Tariq almost 2 years

    I have got a string ["foo","bar","buzz"] from view, i want to remove [,"&,]
    I have used string x = tags.Trim(new Char[] { '[', '"', ']' }); but the output i got is foo","bar","buzz instead of foo,bar,buzz

    enter image description here

    I have tried Trimming & this but still having problem.

    • Corak
      Corak over 5 years
      "creative" approach (not recommended): new string(tags.ToCharArray().Where(c => !"[\"]".Contains(c)).ToArray());
  • Fawad Bin Tariq
    Fawad Bin Tariq over 5 years
    I used this but was looking for some better alternative, regex worked for me :)
  • JMadelaine
    JMadelaine over 5 years
    var trimmed = Regex.Replace(x, @"([|""|])", ""); Added a second doube quote in the regex due to verbatim string literal. The current answer doesn't compile.
  • FCin
    FCin over 5 years
    To 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
    Corak over 5 years
    Also, Trim accepts params, so you can simply write String[] formattedTags = tags.Split(',').Select(item => item.Trim('"', '[', ']')).ToArray(); -- no need for new char[] { ... }
  • Corak
    Corak over 5 years
    @A_Name_Does_Not_Matter - that would be nice, but it seems there is no overload of Replace takes char[] and string.
  • A_Sk
    A_Sk over 5 years
    Yes, there is no overload method... my bad. @Stefan