游戏中显示榜单等重复性信息时, 会有一系列的排序规则。
一般在按照名字排序时,有一条是以汉字拼音字母排序。
本文实现了如何获取汉字的拼音以及拼音首字母的方法。
主要思路:
- GB2312编码采用16位编码方式,简体中文的编码范围从B0A1一直到F7FE,完整编码表链接:http://ash.jp/code/cn/gb2312tbl.htm。
我们通过 System.Text.Encoding.Default.GetBytes()接口可以取到对应的编码数组。 - 汉字拼音的发音是有限的, 且在GB2312中时有序的, 所以我们实现两个数组,一个存放编码, 一个存放拼音,具体的看下方代码。
- 有一些汉字拼音需要作出修正。
- 本文只是一个简单的实现,可以应付一些不精确的场景。 对于多音字等问题, 需要更加专业的解决方案。
测试案例:
class Program {
static void Main(string[] args) {
string testStr = "魔术师大卫说这是个测试";
Console.WriteLine(testStr);
Console.WriteLine("full letters: " + Chinese2Spell.GetFullPinyinLetters(testStr));
Console.WriteLine("first letters: " + Chinese2Spell.GetFirstPinyinLetters(testStr));
Console.ReadKey();
}
}
测试效果:
代码实现:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Spell {
public class Chinese2Spell {
#region 拼音编码
private static int[] pinyinValue = 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,-17733,-17730,
-17721,-17703,-17701,-17697,-17692,-17683,-17676,-17496,-17487,-17482,
-17468,-17454,-17433,-17427,-17417,-17202,-17185,-16983,-16970,-16942,
-16915,-16733,-16708,-16706,-16689,-16664,-16657,-16647,-16474,-16470,
-16465,-16459,-16452,-16448,-16433,-16429,-16427,-16423,-16419,-16412,
-16407,-16403,-16401,-16393,-16220,-16216,-16212,-16205,-16202,-16187,
-16180,-16171,-16169,-16158,-16155,-15959,-15958,-15944,-15933,-15920,
-15915,-15903,-15889,-15878,-15707,-15701,-15681,-15667</