[JAVA]得到漢字的拼音首字母

/**
 * Title:得到漢字的拼音首字母
 * Description: GB 2312-80 把收錄的漢字分紅兩級。第一級漢字是經常使用漢字,計 3755 個,
 * 置於 16~55 區,按漢語拼音字母/筆形順序排列;第二級漢字是次經常使用漢字,
 * 計 3008 個,置於 56~87 區,按部首/筆畫順序排列,因此本程序只能查到
 * 對一級漢字的聲母。同時對符合聲母(zh,ch,sh)只能取首字母(z,c,s) 
 * Copyright: Copyright (c) 2004
 * Company: 
 * @author not attributable
 * @version 1.0
 */
public
class GetFirstLetter { // 國標碼和區位碼轉換常量 private static final int GB_SP_DIFF = 160; //存放國標一級漢字不一樣讀音的起始區位碼 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}; //存放國標一級漢字不一樣讀音的起始區位碼對應讀音 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'}; //獲取一個字符串的拼音碼 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(); } /** 獲取一個漢字的拼音首字母。 * GB碼兩個字節分別減去160,轉換成10進制碼組合就能夠獲得區位碼 * 例如漢字"你"的GB碼是0xC4/0xE3,分別減去0xA0(160)就是0x24/0x43 * 0x24轉成10進制就是36,0x43是67,那麼它的區位碼就是3667,在對照表中讀音爲‘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; } }
相關文章
相關標籤/搜索