Double quotes can be escaped like this:
string test = @"He said to me, ""Hello World"". How are you?";
But this involves adding character "
to the string. Is there a C# function or other method to escape double quotes so that no changing in string is required?
This question is related to
c#
string
double-quotes
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
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
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.
In C#, there are at least 4 ways to embed a quote within a string:
Please refer this document for detailed explanation.
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.
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
Source: Stackoverflow.com