c# string和unicode码的相互转换,代码如下,参照了一些网上信息。运行结果如下如所示。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Test2
{
class Program
{
/// <summary>
/// Unicode解码
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string DeUnicode(string str)
{
try
{
//最直接的方法Regex.Unescape(str);
Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})");//(?i) 表示所在位置右侧的表达式开启忽略大小写模式
return reg.Replace(str, delegate (Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });
}
catch (Exception e)
{
Console.WriteLine("异常信息:" + e.ToString());
return null;
}
}
/// <summary>
/// 字符串转Unicode码
/// </summary>
/// <returns>The to unicode.</returns>
/// <param name="value">Value.</param>
public static string EnUnicode(string value)
{
try
{
byte[] bytes = Encoding.Unicode.GetBytes(value);
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < bytes.Length; i += 2)
{
// 取两个字符,每个字符都是右对齐。
stringBuilder.AppendFormat("\\u{0}{1}", bytes[i + 1].ToString("x").PadLeft(2, '0'), bytes[i].ToString("x").PadLeft(2, '0'));
}
return stringBuilder.ToString();
}
catch (Exception e)
{
Console.WriteLine("异常信息:" + e.ToString());
return null;
}
}
static void Main(string[] args)
{
string str2 = "32abcdef中国";
string str3 = EnUnicode(str2);
string str4 = DeUnicode(str3);
Console.WriteLine("string str2:" + str2);
Console.WriteLine("string编译为unocode码 str3:"+str3);
Console.WriteLine("unocode编译为string码 str4:" + str4);
Console.ReadLine();
}
}
}
运行结果: