I am a bit new to c#, and i am stuck at this point, I have a regular string, where i made use of \
to escape "
, escape here means that to escape the compilers interpretation of "
, and get "
printed on the screen, and i get the expected output-->
class Program { static void Main(string[] args) { string s1 = "This is a \"regular\" string"; System.Console.WriteLine(s1); System.Console.Read(); } }
Now, i have a verbatim string, and i am trying to escape "
using \
in the same manner as above..-->
class Program { static void Main(string[] args) { string s2 = @"This is \t a \"verbatim\" string";//this would escape \t System.Console.WriteLine(s2); System.Console.Read(); } }
Why the above isn't working ?
You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string. Here is an example. The backslashes protect the quotes, but are not printed.
Double Quotes inside verbatim strings can be escaped by using 2 sequential double quotes "" to represent one double quote " in the resulting string. var str = @"""I don't think so,"" he said. "; Console. WriteLine(str);
Escape Double Quotes With the \ Escape Character in C# We can also use the \ escape character to store the string He said "Hi" inside a string variable in C#. We would have to write a \ before each double quote like He said \"Hi\" .
You can use " \\ " instead of " \ " as well as '@' sign in the beginning.
Use a double quote:
string s2 = @"This is \t a ""verbatim"" string";
If you want to write a verbatim string containing a double-quote you must write two double-quotes.
string s2 = @"This is \t a ""verbatim"" string";
This is covered in section 2.4.4.5 of the C# specification:
2.4.4.5 String literals
C# supports two forms of string literals: regular string literals and verbatim string literals.
A regular string literal consists of zero or more characters enclosed in double quotes, as in "hello", and may include both simple escape sequences (such as \t for the tab character) and hexadecimal and Unicode escape sequences.
A verbatim string literal consists of an @ character followed by a double-quote character, zero or more characters, and a closing double-quote character. A simple example is @"hello". In a verbatim string literal, the characters between the delimiters are interpreted verbatim, the only exception being a quote-escape-sequence. In particular, simple escape sequences and hexadecimal and Unicode escape sequences are not processed in verbatim string literals. A verbatim string literal may span multiple lines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With