------------------------------------------------------------------------------
第一种方法: 下面是封装的一个方法。将汉字转为拼音的方法,但是有些字转不了
/// <summary> /// 中文转拼音 /// </summary> /// <param name="str"></param> /// <returns></returns> public String ConvertToPinYin(string str) { string strPinYin = ""; int i = 0; Hashtable htData = Paramer.Json2Hashtable(DataProcessing.strPinYinDict); foreach (char item in str.ToCharArray()) { if (i == 0 && htData.ContainsKey(item.ToString())) { strPinYin += htData[item.ToString()].ToString().ToUpper(); i++; } else { if (Microsoft.International.Converters.PinYinConverter.ChineseChar.IsValidChar(item)) { Microsoft.International.Converters.PinYinConverter.ChineseChar cc = new Microsoft.International.Converters.PinYinConverter.ChineseChar(item); //PYstr += string.Join("", cc.Pinyins.ToArray()); strPinYin += cc.Pinyins[0].Substring(0, cc.Pinyins[0].Length - 1); //PYstr += cc.Pinyins[0].Substring(0, cc.Pinyins[0].Length - 1).Substring(0, 1).ToLower(); } else { strPinYin += item.ToString(); } } } return strPinYin; }
必须 引用了using Microsoft.International.Converters.PinYinConverter;命名空间, 同时引用里面也添加了ChnCharInfo.dll
----第二种方法:Pinyin-的插件比上面那种方法好用------------------------------------------------------------------------
string medicines = "来自中国的南方"; //转换为拼音 string d = Pinyin.GetPinyin(medicines); Console.WriteLine("UTF8句子拼音:"+d); Encoding gb2312 = Encoding.GetEncoding("GB2312"); //转换为拼音的简码 string s = Pinyin.ConvertEncoding(medicines, Encoding.UTF8, gb2312); string d1 = Pinyin.GetInitials(s, gb2312); Console.WriteLine("GB2312拼音简码:"+d1);
需要引用一个插件: NPinyin.dll
来源:https://www.cnblogs.com/cl1006/p/6392624.html