领悟旧事

Learned Helplessness
分类新闻>>技术文章>>
使用微软语言包ChnCharInfo.dll 实现汉字转拼音
来源:http://www.xx0594.com/
时间:2017-4-19
作者:  浏览人数:1042
问题:对于生僻字,没有进行异常处理,如果碰到了,算了倒霉,程序崩溃,无法继续!!如“顾夐”的“夐”字,微软不识字!

    微软自认为很完美!

    ChnCharInfo.dll ,这个是微软官方发布的专门用于处理汉字的工具包,汉字转拼音是完全没问题的。把它放到项目目录的bin文件夹,在项目中右键“引用”——浏览,找到该文件,点确定即可。为确保引用到项目中,最好在项目中的“引用”项看到它后,右键属性,将“复制本地”选为true。

创建一个PinYinHelper类,引入Microsoft.International.Converters.PinYinConverter命名空间。代码:
public static class PinYinHelper    {  
  
     public static string ToPinYin(string txt)  
     {  
         txt = txt.Trim();  
         byte[] arr = new byte[2]; //每个汉字为2字节  
         StringBuilder result = new StringBuilder();//使用StringBuilder优化字符串连接              
         char[] arrChar = txt.ToCharArray();  
         foreach (char c in arrChar)  
         {  
             arr = System.Text.Encoding.Default.GetBytes(c.ToString());//根据系统默认编码得到字节码  
             if (arr.Length == 1)//如果只有1字节说明该字符不是汉字                {  
                 result.Append(c.ToString());  
                 continue;  
             }  
             ChineseChar chineseChar = new ChineseChar(c);  
             result.Append(chineseChar.Pinyins[0].Substring(0, chineseChar.Pinyins[0].Length - 1).ToLower());  
             result.Append(" ");  
         }  
         return result.ToString();  
     }  
 }

关闭窗口
 访问量:507977
任何第三方若要引用、转摘本站信息,均需征得本站书面同意,否则视为侵权。本站信息为个人观点,若因引用本站信息而产生的任何情况,均与本站无关。Email:linmutou@163.com
闽ICP备14017840号-2