I Z
I Z

Reputation: 5927

c#: how to quickly insert a character into string in front of any occurrences of special combinations of characters?

I have a string where I need to escape any occurrences of special combinations of characters. In other words, I need to stick a "\" in front any occurrence of any such combination. Most combinations are actually single characters (e.g a double quote or a backslash) but some are multi-character (e.g. "&&"). One approach is to create an array of strings with these combinations, loop over them and run a String.Replace(), with the backslash being checked the last to avoid recursive escaping. But is there a better (more elegant/quick/etc) way of doing it? Thx

Upvotes: 0

Views: 687

Answers (3)

Zdeslav Vojkovic
Zdeslav Vojkovic

Reputation: 14591

You can use Regex.Replace for this.

var input = @"abc'def&&aa\cc""ff";
var output = Regex.Replace(input, @"'|&&|""|\\", m => @"\" + m); // => "abc\'def\&&aa\\cc\"ff"

Upvotes: 2

Joshua Van Hoesen
Joshua Van Hoesen

Reputation: 1732

you can just take your entire string and run String.Replace() for each replacement type you want to do, As far as I know that is the quickest/most elegant way to do it. Thats why it is a built in method.

Upvotes: 0

Erre Efe
Erre Efe

Reputation: 15557

Use your idea of Replace but using an StringBuilder instead (much better perfomance).

Upvotes: 3

Related Questions