Double quotes can be escaped like this:
string test = @\"He said to me, \"\"Hello World\"\". How are you?\";
But this involves adding chara
You're misunderstanding escaping.
The extra "
characters are part of the string literal; they are interpreted by the compiler as a single "
.
The actual value of your string is still He said to me , "Hello World".How are you ?
, as you'll see if you print it at runtime.
One solution, is to add support to the csharp language so that "" isn't the only scheme used for strings.
For another string terminator to the C# language - I'm a fan of backtick in ES6.
string test = `He said to me, "Hello World". How are you?`;
But also, the doubling idea in Markdown might be better:
string test = ""He said to me, "Hello World". How are you?"";
The code does not work at the date of this post. This post is a solution where the visitors to this Q&A jump onto this csharplank ticket for C# and upvote it - https://github.com/dotnet/csharplang/discussions/3917
In C# you can use the backslash to put special characters to your string. For example, to put ", you need to write \". There are a lot of characters that you write using the backslash: Backslash with a number:
Backslash with othe character
No.
Either use verbatim string literals as you have, or escape the "
using backslash.
string test = "He said to me, \"Hello World\" . How are you?";
The string has not changed in either case - there is a single escaped "
in it. This is just a way to tell C# that the character is part of the string and not a string terminator.
You can use backslash either way;
string str = "He said to me, \"Hello World\". How are you?";
It prints;
He said to me, "Hello World". How are you?
which is exactly same prints with;
string str = @"He said to me, ""Hello World"". How are you?";
Here is a DEMO.
"
is still part of your string.
Check out Escape Sequences and String literals from MSDN.
Please explain your problem. You say:
But this involves adding character " to the string.
What problem is that? You can't type string foo = "Foo"bar"";
, because that'll invoke a compile error. As for the adding part, in string size terms that is not true:
@"""".Length == "\"".Length == 1