How to avoid "in the verbatim line?

I am a little new to C # and I am stuck at this point, I have a regular line where I used \ to exit, escape here means to exclude interpreting " get " compilers printed on the screen and I get the expected result β†’

 class Program { static void Main(string[] args) { string s1 = "This is a \"regular\" string"; System.Console.WriteLine(s1); System.Console.Read(); } } 

o / p -> This is a "regular" string

Now I have a shorthand line, and I'm trying to avoid " using \ in the same way as described above ..-->

 class Program { static void Main(string[] args) { string s2 = @"This is \ta \"verbatim\" string";//this would escape \t System.Console.WriteLine(s2); System.Console.Read(); } } 

Why does the above not work?

+7
source share
3 answers

Use a double quote:

  string s2 = @"This is \ta ""verbatim"" string"; 
+19
source

If you want to write a shorthand string containing a double quote , you must write two double quotation marks.

 string s2 = @"This is \ta ""verbatim"" string"; 

enter image description here

This is described 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 shorthand literals.

A valid string literal consists of zero or more characters enclosed in double quotes, as in "hello", and can include both simple escape sequences (such as \ t for a tab character), as well as hexadecimal and Unicode escape sequences.

A literal 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 shorthand string literal, characters between delimiters are interpreted verbatim, the only exception being the escape sequence. In particular, simple escape sequences and hexadecimal and Unicode escape sequences are not processed in shorthand string literals. A verbal string literal can span multiple lines.

+6
source

In the Verbatim line, backslashes are treated as standard characters, not escape characters. The only character that needs escaping is quotation marks, which you can escape with the same character:

 string s2 = @"This is \ta ""verbatim"" string"; 

Of course, you can never add special characters such as \t (tab) using this method, so this is only useful for simple strings - I think I only ever use this when dealing with file paths.

+3
source

Source: https://habr.com/ru/post/1266618/


All Articles