取得汉字的拼音

过去获取汉字的拼音可不是一件轻松的事情,比较多的做法是利用GB2312码是拼音序的这个特性去获取,但GB2312字符集很少,而更全的GBK编码有许多汉字就不是按照拼音序的了,所以这不是一个很好的方法。

另一种方法则行之有效,我研究出来的,那就是弄了一张全汉字拼音序表,一个个查……虽然可行,但总觉得不够地道。

今天要介绍的方法都不是前面所说的两种,而是直接利用微软提供的库来完成,代码十分简单,直接看:

using Microsoft.International.Converters.PinYinConverter;
namespace PinyinTest
{
    class Program
    {
        static char GetHeadPinyinChar(string strChineseName)
        {
            try
            {
                ChineseChar c = new ChineseChar(strChineseName[0]);
                return c.Pinyins[0][0];
            }
            catch (System.Exception)
            {
                return '#';
            }
        }

        static void Main(string[] args)
        {
            string[] arrNames = new string[] { "王八", "虫虫", "大笨蛋", "黄狗", "大山雀",
                "金狗", "马骝", "肥佬", "阿猫", "三狗", "卢比", "瘦鬼", "罗友", "梁大烟",
                "公牛", "猪队长", "鸡头", "大虫", "蚊子", "阿柴", "阿臭", "邓六", "十八佬", "大颠"};
            Array.Sort(arrNames);
            char cNow = '@';
            foreach (string strName in arrNames)
            {
                char cNew = GetHeadPinyinChar(strName);
                if (cNow != cNew)
                {
                    Console.Write("\n\t" + cNew);
                    cNow = cNew;
                }
                Console.Write("\t" + strName);
            }
            Console.WriteLine("\n");
        }
    }
}

运行结果如下图:

其中引用到的那个库可以在这里下载:https://files.cnblogs.com/guogangj/ChnCharInfo.zip

原文地址:https://www.cnblogs.com/guogangj/p/2470664.html