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;
}

 

posted on 2020-12-11 16:07  炼金师  阅读(122)  评论(0编辑  收藏  举报

导航