【发布时间】:2016-01-16 14:23:00
【问题描述】:
我用 C# 编写了一个方法,它接受一个字符串并转义其所有引号。它转义了它们,因此" 变成了\",它变成了\\\",它变成了\\\\\\\",等等。
这两个参数是input 和depth。深度简单地决定了逃避它的次数。深度为 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