java獲取漢子首字母

public class StringUtil {
//private static Log logger = LogFactory.getLog(StringUtil.class);
//國標碼和區位碼轉換常量

static final int GB_SP_DEFF = 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();
}
/** 獲取一個漢字的拼音首字母。
 * 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_DEFF;
}

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;
}

public static void main(String[] args) {
System.out.println(StringUtil.getFirstLetter("白金"));
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章