日期:2014-05-18  浏览次数:20983 次

如何将字符串转换成转义字符串?
列入 GBK编码的字符串:"你好" 转成 "\xbc\xa0\x09\xa8"

------解决方案--------------------
C# code
        string s = "你好";
        string r = BitConverter.ToString(Encoding.GetEncoding("GBK").GetBytes(s));
        输出r

------解决方案--------------------
C# code

string s = "你好";
byte[] bs = System.Text.Encoding.GetEncoding("GBK").GetBytes(s);
string s1 = string.Empty;
for(int i=0; i < bs.Length; i++)
{
   s1 += @"\x" + bs[i].ToString("x2");
}
Console.WriteLine(s1);

------解决方案--------------------
C# code
var s = @"\xb5\xe7\xd3\xb0\xc5\xc5\xd0\xd0\xd7\xee\xd0\xc2\xc8\xcb\xc6\xf8\xd7\xee\xcd\xfa\xb5\xc4\xc8\xab\xb2\xbf\xca\xd3\xc6\xb5\xcd\xc1\xb6\xb9\xcd\xf8";
var bytes = new byte[s.Length / 4];
for (int i = 0; i < bytes.Length; i++)
{
    bytes[i] = Convert.ToByte(s.Substring(i * 4 + 2, 2), 16);
}
var str = Encoding.GetEncoding("GBK").GetString(bytes);//电影排行最新人气最旺的全部视频土豆网
var nbytes = Encoding.UTF8.GetBytes(str);
var nstr = string.Concat(Array.ConvertAll(nbytes, v1 => @"\x" + Convert.ToString(v1, 16)));
// \xe7\x94\xb5\xe5\xbd\xb1\xe6\x8e\x92\xe8\xa1\x8c\xe6\x9c\x80\xe6\x96\xb0\xe4\xba\xba\xe6\xb0\x94\xe6\x9c\x80\xe6\x97\xba\xe7\x9a\x84\xe5\x85\xa8\xe9\x83\xa8\xe8\xa7\x86\xe9\xa2\x91\xe5\x9c\x9f\xe8\xb1\x86\xe7\xbd\x91

------解决方案--------------------
C# code

                string s = @"\xb5\xe7\xd3\xb0\xc5\xc5\xd0\xd0_\xd7\xee\xd0\xc2\xc8\xcb\xc6\xf8\xd7\xee\xcd\xfa\xb5\xc4\xc8\xab\xb2\xbf\xca\xd3\xc6\xb5_\xcd\xc1\xb6\xb9\xcd\xf8";
                MatchCollection matches = Regex.Matches(s, @"(?i)\\x([0-9a-f]{2})");
                byte[] bytes = new byte[matches.Count];
                for (int i = 0; i < matches.Count; i++)
                    bytes[i] = byte.Parse(matches[i].Groups[1].Value, System.Globalization.NumberStyles.AllowHexSpecifier);
                string r = Encoding.GetEncoding("gbk").GetString(bytes);
                byte[] unicodeBytes = Encoding.Convert(Encoding.GetEncoding("gbk"), Encoding.Unicode, bytes);
                string st = Encoding.Unicode.GetString(unicodeBytes);
                StringBuilder sb = new StringBuilder();
                foreach( char c in st)
                {
                    if( c > 127 )
                    {
                        // This character is too big for ASCII
                        string encodedValue = "\\u" + ((int) c).ToString( "x4" );
                        sb.Append( encodedValue );
                    }
                    else
                    {
                        sb.Append( c );
                    }
                }
                string result = sb.ToString();
                //result = "\u7535\u5f71\u6392\u884c\u6700\u65b0\u4eba\u6c14\u6700\u65fa\u7684\u5168\u90e8\u89c6\u9891\u571f\u8c46\u7f51";