C#怎么判断字符是不是汉字 汉字和Unicode编码互相转换
判断一个字符是不是汉字通常有三种方法,第1种用 ASCII 码判断(在 ASCII码表中,英文的范围是0-127,而汉字则是大于127,根据这个范围可以判断),第2种用汉字的 UNICODE 编码范围判 断(汉字的 UNICODE 编码范围是4e00-9fbb),第3种用正则表达式判断,下面是具体方法。
但是实际上并不怎么准确(从业务上讲,比如全角输入的数字),所以后来简单修改了一下 代码
public static bool IsChinese( this string CString) { bool BoolValue = false; List<string> specialChar = new List<string> { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t" , "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T" , "U", "V", "W", "X", "Y", "Z", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", "0", "'", "[", "]", "|", "\", """, ":", ";", ",", "。", "、", "?" }; for (int i = 0; i < CString.Length; i++) { if (Convert.ToInt32(Convert.ToChar(CString.Substring(i, 1))) < Convert.ToInt32(Convert.ToChar(128))) { BoolValue = false; } else { BoolValue = true; } } if (BoolValue) { if (specialChar.Any(x => CString.Contains(x))) { BoolValue = false; } } return BoolValue; }
当然还有一些特殊字符 也能通过,比如全角输入的π,Ω
public static string String2Unicode(string source) { byte[] bytes = Encoding.Unicode.GetBytes(source); 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(); } public static string Unicode2String(string source) { return new Regex(@"\\u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled).Replace( source, x => string.Empty + Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16))); }
windows技术爱好者
标签:
C#
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构