C#中实现输入汉字获取其拼音(汉字转拼音)的2种方法

2019-12-26 11:23:09王冬梅

    string result = string.Empty;   // 转拼音的结果
    string temp = string.Empty; // 下面foreach用到的临时变量
    foreach (char item in source)   // 遍历每个源字符
    {
        temp = GetPinyin(item.ToString());  // 将每个字符转拼音
        // 处理:获取首字母大写、其余字母小写
        result += (String.Format("{0}{1} ", temp.Substring(0, 1).ToUpper(), temp.Substring(1).ToLower()));
    }

    //string result = GetPinyin(source);  // 调用方法,获取拼音
    this.txt_Pinyin_One.Text = result;
}

 

 OK、到此、这个功能已经实现完成了,还有其余的语言包功能,和此类似,大家可以百度“Microsoft Visual Studio International Pack使用”、各种语言之间的互转及功能示例就出来了。

方式二、手动编码实现

这种方式其实也不困难,说白了就是根据Unicode编码值,定义对应的拼音数组或集合,然后实现此效果。

首先定义拼音区编码数组:

复制代码
//定义拼音区编码数组
private static int[] getValue = new int[]
    {
        -20319,-20317,-20304,-20295,-20292,-20283,-20265,-20257,-20242,-20230,-20051,-20036,
        -20032,-20026,-20002,-19990,-19986,-19982,-19976,-19805,-19784,-19775,-19774,-19763,
        -19756,-19751,-19746,-19741,-19739,-19728,-19725,-19715,-19540,-19531,-19525,-19515,
        -19500,-19484,-19479,-19467,-19289,-19288,-19281,-19275,-19270,-19263,-19261,-19249,
        -19243,-19242,-19238,-19235,-19227,-19224,-19218,-19212,-19038,-19023,-19018,-19006,
        -19003,-18996,-18977,-18961,-18952,-18783,-18774,-18773,-18763,-18756,-18741,-18735,
        -18731,-18722,-18710,-18697,-18696,-18526,-18518,-18501,-18490,-18478,-18463,-18448,
        -18447,-18446,-18239,-18237,-18231,-18220,-18211,-18201,-18184,-18183, -18181,-18012,
        -17997,-17988,-17970,-17964,-17961,-17950,-17947,-17931,-17928,-17922,-17759,-17752,