Silvia Stoyanova
Silvia Stoyanova

Reputation: 281

manipulating strings

I am trying to remove some special characters from a string. I have got the following string

[_fesd][009] Statement

and I want to get rid of all '_' '[' and ']' I managed to remove the first characters with TrimStart and I get fesd][009] Statement

How should I remove the special characters from the middle of my string?

Currently Im using the following code

string newStr = str.Trim(new Char[] { '[', ']', '_' });

where str is the strin that should be manupulated and the result should be stored in newStr

Upvotes: 1

Views: 113

Answers (5)

Kevin Holditch
Kevin Holditch

Reputation: 5313

var newStr = Regex.Replace("[_fesd][009] Statement", "(\\[)|(\\])|(_)", string.Empty);

Upvotes: 1

publicgk
publicgk

Reputation: 3191

var chars = new Char[] { '[', ']', '_' };
var newValue = new String(str.Where(x => !chars.Contains(x)).ToArray());

Upvotes: 0

Alex Filipovici
Alex Filipovici

Reputation: 32581

You could use Linq for it:

static void Main(string[] args)
{
    var s = @"[_fesd][009] Statement";
    var unwanted = @"_[]";

    var sanitizedS = s
        .Where(i => !unwanted.Contains(i))
        .Aggregate<char, string>("", (a, b) => a + b);

    Console.WriteLine(sanitizedS);
    // output: fesd009 Statement
}

Upvotes: 0

It&#39;sNotALie.
It&#39;sNotALie.

Reputation: 22814

Use string.Replace with string.Empty as the string to replace with.

Upvotes: 0

Patrick Quirk
Patrick Quirk

Reputation: 23767

string newStr = str.Replace("[", "").Replace("]", "").Replace("_", "");

Upvotes: 6

Related Questions