Reputation: 5927
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
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
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
Reputation: 15557
Use your idea of Replace but using an StringBuilder instead (much better perfomance).
Upvotes: 3