Kevin Jensen Petersen
Kevin Jensen Petersen

Reputation: 513

Escaping a complicated string

Basicly, I wan't to know how I would go about escaping this:

"\"

By the above, I mean all of the three characters. This is what I've got so far, but which doesn't compile.

t = FindAndReplace("\"SLASH\"", "@\\"\"\\");

So in other words. I have the text "SLASH" which should be replaced by "\" through this.

Upvotes: 0

Views: 75

Answers (2)

Polynomial
Polynomial

Reputation: 3706

You need to escape the first quote as \", then escape the slash as \\, then the final quote again with \". The whole thing is then wrapped in quotes, like this:

t = FindAndReplace("\"SLASH\"", "\"\\\"");

The @ notation is useful when your string contains many backslash tokens and you don't want to have to escape them all, for example in path names:

string x = "C:\\Program Files\\Microsoft\\Some Folder\\";

Is functionally equivalent to:

string x = @"C:\Program Files\Microsoft\Some Folder\";

Using @ notation permits quotes to be encoded by writing them twice, so the potentially more readable answer to the original question is:

t = FindAndReplace("\"SLASH\"", @"""\""");

Upvotes: 3

JSFernandes
JSFernandes

Reputation: 188

Your second tring is actually being seen as

"@\"\"\"

Which is two strings with an "\" in the middle. For your very first question, the answer is:

"\"\\\""

If this isn't what you mean in your code, then please clarify your question.

Upvotes: 0

Related Questions