VS Code 2019中转义字符\输出异常,如何正确添加双引号?
Hey there! Let's break down why you're seeing those extra escape characters and how to get the output you want.
What's Happening Now
First, let's clarify your actual code (since the " in your question is just an HTML entity for double quotes):
string sample = "How to add doublequotes"; string str = "\"" + sample + "\"";
When you look at this string in VS Code's debug output or watch window, it shows up as \"How to add doublequotes\"—but this is just the debugger's way of displaying the string to let you see the special characters it contains. The actual content of the string does include the double quotes, not the \ escape characters.
If you were to output this string to the console (using Console.WriteLine(str);) or write it to a file, you'd see exactly what you want: "How to add doublequotes".
Cleaner Ways to Write This
If you want to avoid dealing with escape characters in your code, here are two better approaches:
String Interpolation (C# 6+): This is the most readable option. Wrap your variable in curly braces inside a string prefixed with
$:string str = $"\"{sample}\"";Verbatim Strings: Use
@to create a verbatim string, where double quotes are escaped by doubling them:string str = @"""" + sample + @"""";Or combine it with interpolation for even cleaner code:
string str = $@"""{sample}""";
Verify the Actual String Content
To confirm the string has the correct content without escape characters, run this code:
Console.WriteLine(str);
You'll see the output you're expecting: "How to add doublequotes".
The extra \ you're seeing is just a visual artifact of the debugger's display, not part of the actual string value.
内容的提问来源于stack exchange,提问作者Siddharth Kumar Shukla

