1. 程式人生 > 實用技巧 >C#版escape unescape

C#版escape unescape

/// <summary>
/// Escape方法
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string Escape(string s)
{
    StringBuilder sb = new StringBuilder();
    byte[] byteArr = Encoding.Unicode.GetBytes(s);
    for (int i = 0; i < byteArr.Length; i += 2)
    {
        sb.Append(
"%u"); sb.Append(byteArr[i + 1].ToString("X2"));//把位元組轉換為十六進位制的字串表現形式 sb.Append(byteArr[i].ToString("X2")); } return sb.ToString(); } /// <summary> /// UnEscape方法 /// </summary> /// <param name="s"></param> /// <returns></returns> public static string UnEscape(string
s) { string str = s.Remove(0, 2);//刪除最前面兩個"%u" string[] strArr = str.Split(new string[] { "%u" }, StringSplitOptions.None);//以子字串"%u"分隔 byte[] byteArr = new byte[strArr.Length * 2]; for (int i = 0, j = 0; i < strArr.Length; i++, j += 2) { byteArr[j + 1] = Convert.ToByte(strArr[i].Substring(0
, 2), 16); //把十六進位制形式的字串符串轉換為二進位制位元組 byteArr[j] = Convert.ToByte(strArr[i].Substring(2, 2), 16); } str = Encoding.Unicode.GetString(byteArr); //把位元組轉為unicode編碼 return str; }