C# 实现 Unicode 字符串 转换
啥也不多说,直接上干货
/// <summary>
/// 对正常的字符串转换为 Unicode 的字符串
/// </summary>
/// <param name="normalStr">正常的字符串</param>
/// <param name="isIgnoreSpace">是否忽略空格符;默认 true 空格符不转换;false 空格符要转换</param>
/// <param name="isUpperCaseU">是否大写U字母 ‘\U’;默认 false ‘\u’</param>
/// <returns></returns>
public static string ToUnicode(this string normalStr, bool isIgnoreSpace = true, bool isUpperCaseU = false)
{
if (string.IsNullOrEmpty(normalStr))
{
return string.Empty;
}
StringBuilder strResult = new StringBuilder();
void func(int index)
{
if (isUpperCaseU)
{
strResult.Append("\\U");
}
else
{
strResult.Append("\\u");
}
strResult.Append(((int)normalStr[index]).ToString("x").PadLeft(4, '0'));
}
for (int i = 0; i < normalStr.Length; i++)
{
if (isIgnoreSpace)
{
if (normalStr[i] == ' ')
{
strResult.Append(" ");
}
else
{
func(i);
}
}
else
{
func(i);
}
}
return strResult.ToString();
}
/// <summary>
/// 对 Unicode 的字符串解码
/// </summary>
/// <param name="unicodeStr">Unicode 字符串</param>
/// <returns></returns>
public static string UnicodeDecode(this string unicodeStr)
{
if (string.IsNullOrWhiteSpace(unicodeStr) || (!unicodeStr.Contains("\\u") && !unicodeStr.Contains("\\U")))
{
return unicodeStr;
}
string newStr = Regex.Replace(unicodeStr, @"\\[uU](.{4})", (m) =>
{
string unicode = m.Groups[1].Value;
if (int.TryParse(unicode, System.Globalization.NumberStyles.HexNumber, null, out int temp))
{
return ((char)temp).ToString();
}
else
{
return m.Groups[0].Value;
}
}, RegexOptions.Singleline);
return newStr;
}
测试示例:
// 测试 Unicode 转码
{
string str = @"\u00f3fdsf \u00f9\U00f3 \U +e9\u00e9";
string newStr = str.UnicodeDecode();
Console.WriteLine(newStr);
Console.WriteLine();
newStr = "0 - * @ , 。 ? 发动 繁體字".ToUnicode();
Console.WriteLine(newStr);
Console.WriteLine();
}