前言:
在一些手机通讯录或者一些需要排列汉字的情况下我们需要按照汉字的首写字母去索引一些联系人或者汉字,让你排列汉字或许你没有头绪。让你排列A、B、C..等字母你应该头不会那么大了吧?最起码自定义顺序之后去挨个判断等于的关系也可以排列(当然有的大神有其他的方法,在此我也不在叙述),最简单的莫过于对数字的排列。我这么说大家应该没有意见吧?下面进入正题
测试结果截图:
OK,大家看到日志的输出是正确的。下面我给大家说一下实现原理并上传一下源码
实现原理:
通过汉字的编码我们拿到这个汉字对应的字节码,也就是我们的getBytes方法。然后算出此汉字对应的数值。然后比较判断此汉字所在的数值参考区间。然后拿到对应的区间,并且查询对应的首字母。
程序片段:
public class testmain {
//用于参考判断区间的字节码获取值
private static char[] chartable =
{
'啊', '芭', '擦', '搭', '蛾', '发', '噶', '哈', '哈',
'击', '喀', '垃', '妈', '拿', '哦', '啪', '期', '然',
'撒', '塌', '塌', '塌', '挖', '昔', '压', '匝', '座'
};
//用于返回的值数组
private static char[] alphatable =
{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
};
//汉子字节码对应数值区间
private static int[] tablechar = new int[27];
//初始化标准区间对应的相应字节码数值
static{
for(int i = 0 ; i < chartable.length;i++){
tablechar[i] = ChineseToCode(chartable[i]);
}
}
//获取相应汉子对应的字节码数值
public static int ChineseToCode(char chinese){
int code = 0;
try {
String a = "";
a+=chinese;
byte[] bytes = a.getBytes("GB2312"); //获取字节码
code = (bytes[0] << 8 & 0xff00) + (bytes[1] &
0xff); //最终字节码对应的数值code的算法
} catch (Exception e) {
// TODO: handle exception
}
return code;
}
//
public static char CodeToEng(int code){
int currentindex = 0;
try {
for(int i = 0 ; i < 26 ; i++){
if(code < tablechar[0]){
return 0;
}
if(code > tablechar[26]){
return 0;
}
int j = i+1;
if(code > tablechar[i] && code <= tablechar[j]){
//为T的情况
if(tablechar[i] == tablechar[i-1] && tablechar[i] == tablechar[i-2]){
i = i-2;
}
//为H的情况
if(tablechar[i] == tablechar[i-1]){
i = i-1;
}
currentindex = i;
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return alphatable[currentindex];
}
public static void main(String[] args) {
String result = "";
String teststr = "中华人民共和国";
int len = teststr.length();
try {
for(int i = 0; i < len ; i ++){
char a = teststr.charAt(i);
int code = ChineseToCode(a); //获取汉字对应的字节码数值
char k = CodeToEng(code); //通过字节码数值判断区间获取相应的首字母
result+=k;
}
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
注意:
其中IUV不做声母。我做了相关处理(即重复几个汉字)。
程序的注释可读性很高。自己试着读读吧.
源码中有两个版本。一个是我自己写的。另外一个版是参考的版本。都给大家了。
源码下载地址:
http://pan.baidu.com/share/link?shareid=486476&uk=1997312776