How do I escape " in verbatim string? [duplicate]

淺唱寂寞╮ 提交于 2019-12-04 02:45:09

问题


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();
    }
}

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

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 ?


回答1:


Use a double quote:

 string s2 = @"This is \t a ""verbatim"" string";



回答2:


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.




回答3:


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

string s2 = @"This is \t a ""verbatim"" string";

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



来源:https://stackoverflow.com/questions/17168961/how-do-i-escape-in-verbatim-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!