0
我在C#中編寫了一個方法,它接受一個字符串並轉義所有引號。它逃脫它們,使"
變成\"
,變成\\\"
,變成\\\\\\\"
等等。在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。它只能工作到20,基本上很糟糕。
本身,我認爲它可以正常工作,但我稍後會在循環中重複調用它,並且每次調用它時都會有40個循環會嚴重影響性能。
任何想法如何清理這件事?我仍然認爲自己是一個業餘愛好者,所以我可能會錯過一些非常簡單的事情,但我的搜索沒有發現任何有用的東西。
這只是一個堅持反斜槓等於每個引號後面的深度。它需要以0,1,3,7,15,31等模式轉義。 – tryashtar
好的,所以你使用的是Mersenne數字序列。現在就試試。 – DavidG
這很簡單,我覺得自己像一個白癡。謝謝你的幫助! – tryashtar