You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VS Code 2019中转义字符\输出异常,如何正确添加双引号?

Fixing Unwanted Escape Characters When Adding Double Quotes in C#

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:59:58