C# 将单引号转换为字符串中的转义单引号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10728602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:01:23  来源:igfitidea点击:

Turning a single quote into an escaped single quote within a string

c#stringreplaceescaping

提问by Justin Helgerson

It pains me to ask this, but, for some reason I have not been able to get this to work (it's late in the day, yes, that's my excuse).

问这个问题让我很痛苦,但是,由于某种原因,我无法让它发挥作用(今天已经很晚了,是的,这是我的借口)。

Let's say I have this string:

假设我有这个字符串:

s = "John's book."

Using the replacemethod from the object String, I want to turn it into this:

使用replace对象String中的方法,我想把它变成这样:

s = "John\'s book."

I would have expected this code to give me what I want:

我本来希望这段代码能给我我想要的东西:

s = s.Replace("'", "\'")

But, that results in:

但是,这导致:

"John\'s book."

采纳答案by BeemerGuy

Do this so you don't have to think about it:

这样做,你就不必考虑它:

s = s.Replace("'", @"\'");

回答by JohnP

I have a quick and dirty function to escape text before using in a mysql insert clause, this might help:

在 mysql 插入子句中使用之前,我有一个快速而肮脏的函数来转义文本,这可能会有所帮助:

    public static string MySqlEscape(Object usString)
    {
        if (usString is DBNull)
        {
            return "";
        }
        else
        {
            string sample = Convert.ToString(usString);
            return Regex.Replace(sample, @"[\r\n\x00\x1a\'""]", @"$0");
        }
    }

回答by Virendra Shenvi Velingkar

Simplest one would be

最简单的一个是

Server.HtmlEncode(varYourString);

回答by Richard Duerr

Just to show another possible solution if this pertaining to MVC.NET (MVC5+):

只是为了展示另一种可能的解决方案,如果这与 MVC.NET (MVC5+) 有关:

var data= JSON.parse('@Html.Raw(HttpUtility.JavaScriptStringEncode(JsonConvert.SerializeObject(Model.memberObj)))');

This allows you to escape AND pass data to views as JavaScript. The key part is:

这允许您转义并将数据作为 JavaScript 传递给视图。关键部分是:

HttpUtility.JavaScriptStringEncode