【问题标题】:Using \ as a escape character is giving an unexpected output [duplicate]使用 \ 作为转义字符会产生意外的输出 [重复]
【发布时间】:2020-12-19 12:47:33
【问题描述】:

string sample="如何添加双引号"; 字符串 str = '"'+sample+'"';

这是我得到的输出 - "\"How to add doublequotes\"" 我希望输出为str= "How to add doublequotes" 我正在使用 vs code19

【问题讨论】:

  • 我什至尝试使用 \ 和 @,但得到相同的输出
  • 当你说“输出”是什么意思?你跑Console.WriteLine(str)了吗?
  • 我在调试器输出中放了一个调试器,它显示了这个
  • 试试 str = str.Replace("\",string.empty) 你会得到同样的结果——你看到的字符串只是在调试器中。

标签: c# asp.net string


【解决方案1】:

调试器中显示的输出不是您将在屏幕上收到的输出。
将其打印到 [Console / API / Website] 时,一切都会按预期工作。

要明白我的意思,请尝试在 Main 上使用以下代码创建一个控制台应用程序:

static void Main(string[] args)
{
    string str = "\"This is with doublequotes\"";
    Console.WriteLine(str);
}  

顺便说一句:你可以写string str = "\"How to add doublequotes\"",它仍然可以工作。

【讨论】:

  • 我必须在查询字符串中使用它,即类似这样- Select * from tbl where Username=username 假设 username="abc" 的值 现在,在查询字符串中,它变成 - Select * from tbl where username=abc 它应该是这样的 Select * from tbl where username="abc" 希望你明白我的意思!
  • @SiddharthKumarShukla 同样适用于查询。如果string username = "abc" 那么Select * from tbl where username=\"" + username + "\""
  • @Administrator 不鼓励 SQL 注入
【解决方案2】:

如果您在文本中使用特殊字符或换行符,则可以使用逐字字符串。它们通过在字符串前放置一个 @ 来表示。在逐字字符串中,您不再需要转义特殊字符,但有一个例外:双引号 " 需要使用另一个双引号进行转义:

string sample = @""How to add double quotes"";

将逐字字符串与插值字符串组合时,应将 $ 放在首位:

string sample = $@"He said: ""Yes, for sure!"", but was only {p.Value} ÷ sure about it.";

【讨论】:

    【解决方案3】:

    使用this解决了错误-

    string query = "select * from customer where country = '" + USERNAME + "'";
    

    感谢大家投入宝贵的时间!

    【讨论】:

    • 不要这样做。请阅读副本。
    猜你喜欢
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 2021-09-21
    • 2015-10-29
    相关资源
    最近更新 更多