【问题标题】:Escape the quotes in a C# string转义 C# 字符串中的引号
【发布时间】:2016-01-16 14:23:00
【问题描述】:

我用 C# 编写了一个方法,它接受一个字符串并转义其所有引号。它转义了它们,因此" 变成了\",它变成了\\\",它变成了\\\\\\\",等等。

这两个参数是inputdepth。深度简单地决定了逃避它的次数。深度为 1 时,字符串 He says "hello" 变为 He says \"hello\",而深度为 2 时,字符串变为 He says \\\"hello\\\"

private string escapestring(string input, int depth)
    {
        string result = input;
        for (int i = 20; i >= 0; i--)
        {
            int nsearch = ((int)Math.Pow(2, i)) - 1;
            int nplus = ((int)Math.Pow(2, i + depth) - 1);
            string search = new string('\\', nsearch);
            search += "\"";
            result = result.Replace(search, "ESCAPE_REPLACE:" + (nplus).ToString());
        }
        for (int i = 20; i >= 0; i--)
        {
            int nsearch = ((int)Math.Pow(2, i)) - 1;
            string replace = new string('\\', nsearch);
            replace += "\"";
            result = result.Replace("ESCAPE_REPLACE:" + nsearch.ToString(), replace);
        }
        return result;
    }

这是我为解决此任务而创建的。这真的很可怕,只需将每组反斜杠替换为符合 2^X-1 模式的引号,然后用一些任意 blob 替换任意 blob,然后用转义版本替换任意 blob。它最多只能工作 20 并且基本上很糟糕。

就其本身而言,我想它会正常工作,但我稍后会在循环中反复调用它,每次调用它时的 40 个循环都会严重影响性能。

关于如何清理这个东西有什么想法吗?我仍然认为自己是一个业余爱好者,所以我可能会遗漏一些非常简单的东西,但我的搜索没有发现任何有用的东西。

【问题讨论】:

    标签: c# string replace escaping


    【解决方案1】:

    不确定所有数学的用途,但这会做到:

    private string escapestring(string input, int depth)
    {
        var numSlashes = (int)(Math.Pow(2, depth)-1);
        return input.Replace("\"", new string('\\', numSlashes)+"\"");
    }
    

    【讨论】:

    • 这只是在每个引号后面加上一些等于深度的反斜杠。它需要以0、1、3、7、15、31等模式进行转义。
    • 好的,所以您使用的是梅森数列。立即尝试。
    • 这太简单了,我觉得自己像个白痴。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    相关资源
    最近更新 更多