C# 汉字转拼音
安装相关依赖:NPinyin
Microsoft.International.Converters.PinYinConverter
直接从vs里面的nuget管理器搜索下载即可。
public class PinYinHelper { private static Encoding gb2312 = Encoding.GetEncoding("GB2312"); /// <summary> /// 汉字转全拼 /// </summary> public static string ConvertToAllSpell(string strChinese, IDictionary<char, string> pinyinDic = null) { try { if (strChinese.Length != 0) { var fullSpell = new StringBuilder(); for (var i = 0; i < strChinese.Length; i++) { var chr = strChinese[i]; var pinyin = GetSpell(chr); fullSpell.Append(pinyin); } return fullSpell.ToString().ToLower(); } } catch (Exception e) { Console.WriteLine("全拼转化出错!" + e.Message); } return string.Empty; } /// <summary> /// 汉字转首字母 /// </summary> /// <param name="strChinese"></param> /// <returns></returns> public static string GetFirstSpell(string strChinese) { //NPinyin.Pinyin.GetInitials(strChinese) 有Bug 洺无法识别 //return NPinyin.Pinyin.GetInitials(strChinese); try { if (strChinese.Length != 0) { var fullSpell = new StringBuilder(); for (var i = 0; i < strChinese.Length; i++) { var chr = strChinese[i]; fullSpell.Append(GetSpell(chr)[0]); } return fullSpell.ToString().ToLower(); } } catch (Exception e) { Console.WriteLine("首字母转化出错!" + e.Message); } return string.Empty; } private static string GetSpell(char chr) { var coverchr = NPinyin.Pinyin.GetPinyin(chr); var isChineses = ChineseChar.IsValidChar(coverchr[0]); if (isChineses) { var chineseChar = new ChineseChar(coverchr[0]); foreach (var value in chineseChar.Pinyins) { if (!string.IsNullOrEmpty(value)) { return value.Remove(value.Length - 1, 1); } } } return coverchr; } /// <summary> /// 从字典获取拼音 /// </summary> /// <param name="c">字</param> /// <param name="pinyinDic">字典</param> /// <returns></returns> private static string GetFromPinYinDic(char c, IDictionary<char, string> pinyinDic) { if (pinyinDic == null || pinyinDic.Count == 0 || !pinyinDic.ContainsKey(c)) { return ""; } return pinyinDic[c]; } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤