在項目中要更能根據某些查詢條件(比如姓名)的首字母作為條件進行查詢,比如查一個叫“張三”的人,可以輸入‘zs'。寫瞭一個工具類如下:
/**GB 2312-80 把收錄的漢字分成兩級。第一級漢字是常用漢字,計 3755 個,
* 置於 16~55 區,按漢語拼音字母/筆形順序排列;第二級漢字是次常用漢字,
* 計 3008 個,置於 56~87 區,按部首/筆畫順序排列,所以本程序隻能查到
* 對一級漢字的聲母。同時對符合聲母(zh,ch,sh)隻能取首字母(z,c,s)
*/
Java代碼
static final int GB_SP_DIFF = 160;
// 存放國標一級漢字不同讀音的起始區位碼
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 };
// 存放國標一級漢字不同讀音的起始區位碼對應讀音
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' };
// 獲取一個字符串的拼音碼
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中每個字符
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();
}
// 獲取一個漢字的拼音碼
public static Character getFirstLetter(char ch) {
byte[] uniCode = null;
try {
uniCode = String.valueOf(ch).getBytes("GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
if (uniCode[0] < 128 && uniCode[0] > 0) { // 非漢字
return null;
} else {
return convert(uniCode);
}
}
/**
* 獲取一個漢字的拼音首字母。 GB碼兩個字節分別減去160,轉換成10進制碼組合就可以得到區位碼
* 例如漢字“你”的GB碼是0xC4/0xE3,分別減去0xA0(160)就是0x24/0x43
* 0x24轉成10進制就是36,0x43是67,那麼它的區位碼就是3667,在對照表中讀音為‘n’
*/
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;
}
作者“eric-gcm”