How to convert a string containing escape characters to a string

前端 未结 4 2230
心在旅途
心在旅途 2020-12-11 19:25

I have a string that is returned to me which contains escape characters.

Here is a sample string

\"test\\40gmail.com\"

A

4条回答
  •  被撕碎了的回忆
    2020-12-11 19:52

    I just wrote this piece of code and it seems to work beautifully... It requires that the escape sequence is in HEX, and is valid for value's 0x00 to 0xFF.

    // Example
    str = remEscChars(@"Test\x0D") // str = "Test\r"
    

    Here is the code.

    private string remEscChars(string str)
    {
       int pos = 0;
       string subStr = null;
       string escStr = null;
    
       try
       {
          while ((pos = str.IndexOf(@"\x")) >= 0)
          {
             subStr = str.Substring(pos + 2, 2);
             escStr = Convert.ToString(Convert.ToChar(Convert.ToInt32(subStr, 16)));
             str = str.Replace(@"\x" + subStr, escStr);
          }
       }
       catch (Exception ex)
       {
          throw ex;
       }
    
       return str;
    }
    

提交回复
热议问题