using System; using System.Diagnostics; using Microsoft.International.Converters.PinYinConverter; namespace TestPinYin { namespace NPinyinTest { class Program { /// <summary> /// 汉字转化为拼音 /// </summary> /// <param name="str">汉字</param> /// <returns>全拼</returns> public static string GetPinyin(string str) { string r = string.Empty; foreach (char obj in str) { try { ChineseChar chineseChar = new ChineseChar(obj); string t = chineseChar.Pinyins[0].ToString(); r += t.Substring(0, t.Length - 1); } catch { r += obj.ToString(); } } return r; } /// <summary> /// 汉字转化为拼音首字母 /// </summary> /// <param name="str">汉字</param> /// <returns>首字母</returns> public static string GetFirstPinyin(string str) { string r = string.Empty; foreach (char obj in str) { try { ChineseChar chineseChar = new ChineseChar(obj); string t = chineseChar.Pinyins[0].ToString(); r += t.Substring(0, 1); } catch { r += obj.ToString(); } } return r; } /// <summary> /// 获取字符的第一个单词 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string GetFirstCode(string str) { if (string.IsNullOrEmpty(str)) return string.Empty; var chararry = str.ToCharArray(); try { ChineseChar chineseChar = new ChineseChar(chararry[0]); string t = chineseChar.Pinyins[0].ToString(); return t.Substring(0, 1); } catch { return chararry[0].ToString().ToUpper(); } } static void Main(string[] args) { Stopwatch sw = new Stopwatch(); sw.Start();//开始计时 string[] maxims = new string[]{ "事常与人违,事总在人为", "骏马是跑出来的,强兵是打出来的", "驾驭命运的舵是奋斗。不抱有一丝幻想,不放弃一点机会,不停止一日努力。 ", "如果惧怕前面跌宕的山岩,生命就永远只能是死水一潭", "懦弱的人只会裹足不前,莽撞的人只能引为烧身,只有真正勇敢的人才能所向披靡" }; string[] medicines = new string[] { "聚维酮碘溶液", "开塞露", "炉甘石洗剂", "苯扎氯铵贴", "鱼石脂软膏", "莫匹罗星软膏", "红霉素软膏", "氢化可的松软膏", "曲安奈德软膏", "丁苯羟酸乳膏", "双氯芬酸二乙胺乳膏", "冻疮膏", "克霉唑软膏", "特比奈芬软膏", "酞丁安软膏", "咪康唑软膏、栓剂", "甲硝唑栓", "复方莪术油栓" }; Console.WriteLine("UTF8句子拼音:"); foreach (string s in maxims) { Console.WriteLine("汉字:{0} 拼音:{1} ", s, GetPinyin(s)); } Console.WriteLine("GB2312拼音简码:"); foreach (string m in medicines) { Console.WriteLine("药品:{0} 简码:{1} ", m, GetFirstPinyin(m)); Console.WriteLine("药品:{0} 首字母:{1} ", m, GetFirstCode(m)); } sw.Stop();//结束计时 Console.WriteLine("执行耗时:" + sw.Elapsed); Console.ReadKey(); } } } }