2015-10-18 111 views
0

我在C#中編寫了一個方法,它接受一個字符串並轉義所有引號。它逃脫它們,使"變成\",變成\\\",變成\\\\\\\"等等。在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。它只能工作到20,基本上很糟糕。

本身,我認爲它可以正常工作,但我稍後會在循環中重複調用它,並且每次調用它時都會有40個循環會嚴重影響性能。

任何想法如何清理這件事?我仍然認爲自己是一個業餘愛好者,所以我可能會錯過一些非常簡單的事情,但我的搜索沒有發現任何有用的東西。

回答

2

不知道什麼所有的數學是,但是這將做到這一點:

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

這只是一個堅持反斜槓等於每個引號後面的深度。它需要以0,1,3,7,15,31等模式轉義。 – tryashtar

+0

好的,所以你使用的是Mersenne數字序列。現在就試試。 – DavidG

+0

這很簡單,我覺得自己像一個白癡。謝謝你的幫助! – tryashtar