--sunfruit
提供了獲得漢字的拼音首字母的方法
JDK版本 無(wú)版本限制
功能 實(shí)現(xiàn)了獲得一個(gè)漢字的拼音首字母功能,為漢字排序提供了方便
歡迎大家提意見,交流
代碼如下:
/**
* Title:獲得漢字的拼音首字母
* Description: GB 2312-80 把收錄的漢字分成兩級(jí)。第一級(jí)漢字是常用漢字,計(jì) 3755 個(gè),
* 置于 16~55 區(qū),按漢語(yǔ)拼音字母/筆形順序排列;第二級(jí)漢字是次常用漢字,
* 計(jì) 3008 個(gè),置于 56~87 區(qū),按部首/筆畫順序排列,所以本程序只能查到
* 對(duì)一級(jí)漢字的聲母。同時(shí)對(duì)符合聲母(zh,ch,sh)只能取首字母(z,c,s)
* Copyright: Copyright (c) 2004
* Company:
* @author not attributable
* @version 1.0
*/
public class GetFirstLetter {
// 國(guó)標(biāo)碼和區(qū)位碼轉(zhuǎn)換常量
private static final int GB_SP_DIFF = 160;
//存放國(guó)標(biāo)一級(jí)漢字不同讀音的起始區(qū)位碼
private static final int[] secPosvalueList = {
1601, 1637, 1833, 2078, 2274, 2302, 2433, 2594, 2787,
3106, 3212, 3472, 3635, 3722, 3730, 3858, 4027, 4086,
4390, 4558, 4684, 4925, 5249, 5600};
//存放國(guó)標(biāo)一級(jí)漢字不同讀音的起始區(qū)位碼對(duì)應(yīng)讀音
private static final char[] firstLetter = {
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
't', 'w', 'x', 'y', 'z'};
//獲取一個(gè)字符串的拼音碼
public static String getFirstLetter(String oriStr) {
String str = oriStr.toLowerCase();
StringBuffer buffer = new StringBuffer();
char ch;
char[] temp;
for (int i = 0; i < str.length(); i++) { //依次處理str中每個(gè)字符
ch = str.charAt(i);
temp = new char[] {
ch};
byte[] uniCode = new String(temp).getBytes();
if (uniCode[0] < 128 && uniCode[0] > 0) { // 非漢字
buffer.append(temp);
}
else {
buffer.append(convert(uniCode));
}
}
return buffer.toString();
}
/** 獲取一個(gè)漢字的拼音首字母。
* GB碼兩個(gè)字節(jié)分別減去160,轉(zhuǎn)換成10進(jìn)制碼組合就可以得到區(qū)位碼
* 例如漢字"你"的GB碼是0xC4/0xE3,分別減去0xA0(160)就是0x24/0x43
* 0x24轉(zhuǎn)成10進(jìn)制就是36,0x43是67,那么它的區(qū)位碼就是3667,在對(duì)照表中讀音為‘n'
*/
private static char convert(byte[] bytes) {
char result = '-';
int secPosvalue = 0;
int i;
for (i = 0; i < bytes.length; i++) {
bytes[i] -= GB_SP_DIFF;
}
secPosvalue = bytes[0] * 100 + bytes[1];
for (i = 0; i < 23; i++) {
if (secPosvalue >= secPosvalueList[i] &&
secPosvalue < secPosvalueList[i + 1]) {
result = firstLetter[i];
break;
}
}
return result;
}
}