C# Unicode编码解码的实现

本文主要介绍了C# Unicode编码解码的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

Unicode是计算机科学领域里的一项业界标准,包括字符集、编码方案等。Unicode 是为了解决传统的字符编码方案的局限而产生的,它为每种语言中的每个字符设定了统一并且唯一的二进制编码,以满足跨语言、跨平台进行文本转换、处理的要求。

在这里插入图片描述

在表示一个Unicode的字符时,通常会用“U+”然后紧接着一组十六进制的数字来表示这一个字符。在 基本多文种平面里的所有字符,要用四位十六进制数;在零号平面以外的字符则需要使用五位或六位十六进制数了。

string str = @"\u0005 \u0002\U00f3 \U +e9\u00e9"; string newStr = UnicodeDecode(str); Console.WriteLine(newStr); Console.WriteLine(); newStr = ToUnicode("0 - * @ , 。 ? 真的 繁體字"); Console.WriteLine(newStr); Console.WriteLine(); 

正常字符转换为unicode

        ///  /// 对正常的字符串转换为 Unicode 的字符串 ///  /// 正常的字符串 /// 是否忽略空格符;默认 true 空格符不转换;false 空格符要转换 /// 是否大写U字母 ‘\U';默认 false ‘\u' ///  public 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 

解码

        ///  /// 对 Unicode 的字符串解码 ///  /// Unicode 字符串 ///  public string UnicodeDecode(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; } 

到此这篇关于C# Unicode编码解码的实现的文章就介绍到这了,更多相关C# Unicode编码解码内容请搜索0133技术站以前的文章或继续浏览下面的相关文章希望大家以后多多支持0133技术站!

以上就是C# Unicode编码解码的实现的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 其他教程