本文實(shí)例講述了java獲取中文拼音首字母工具類定義與用法。分享給大家供大家參考,具體如下:

package com.sw.documentary.common.utils;
public class GB2Alpha {
//字母Z使用了兩個(gè)標(biāo)簽,這里有27個(gè)值
//i, u, v都不做聲母, 跟隨前面的字母
private char[] chartable =
{
'啊', '芭', '擦', '搭', '蛾', '發(fā)', '噶', '哈', '哈',
'擊', '喀', '垃', '媽', '拿', '哦', '啪', '期', '然',
'撒', '塌', '塌', '塌', '挖', '昔', '壓', '匝', '座'
};
private 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 int[] table = new int[27];
//初始化
{
for (int i = 0; i < 27; ++i) {
table[i] = gbValue(chartable[i]);
}
}
public GB2Alpha() {
}
//主函數(shù),輸入字符,得到他的聲母,
//英文字母返回對(duì)應(yīng)的大寫字母
//其他非簡體漢字返回 '0'
public char Char2Alpha(char ch) {
if (ch >= 'a' && ch <= 'z')
return (char) (ch - 'a' + 'A');
if (ch >= 'A' && ch <= 'Z')
return ch;
int gb = gbValue(ch);
if (gb < table[0])
return '0';
int i;
for (i = 0; i < 26; ++i) {
if (match(i, gb)) break;
}
if (i >= 26)
return '0';
else
return alphatable[i];
}
//根據(jù)一個(gè)包含漢字的字符串返回一個(gè)漢字拼音首字母的字符串
public String String2Alpha(String SourceStr){
String Result = "";
int StrLength = SourceStr.length();
int i;
try {
for (i = 0; i < StrLength; i++) {
Result += Char2Alpha(SourceStr.charAt(i));
}
} catch (Exception e) {
Result = "";
}
return Result;
}
private boolean match(int i, int gb) {
if (gb < table[i])
return false;
int j = i + 1;
//字母Z使用了兩個(gè)標(biāo)簽
while (j < 26 && (table[j] == table[i])) ++j;
if (j == 26)
return gb <= table[j];
else
return gb < table[j];
}
//取出漢字的編碼
private int gbValue(char ch) {
String str = new String();
str += ch;
try {
byte[] bytes = str.getBytes("GB2312");
if (bytes.length < 2)
return 0;
return (bytes[0] << 8 & 0xff00) + (bytes[1] &
0xff);
} catch (Exception e) {
return 0;
}
}
public static void main(String[] args) {
GB2Alpha obj1 = new GB2Alpha();
System.out.println(obj1.String2Alpha("創(chuàng)新互聯(lián)建站"));
System.out.println(obj1.String2Alpha("歡迎你"));
return;
}
}
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)建站www.chinadenli.net,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。
文章標(biāo)題:java獲取中文拼音首字母工具類定義與用法實(shí)例-創(chuàng)新互聯(lián)
轉(zhuǎn)載源于:http://www.chinadenli.net/article6/dehpog.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供手機(jī)網(wǎng)站建設(shè)、動(dòng)態(tài)網(wǎng)站、Google、全網(wǎng)營銷推廣、標(biāo)簽優(yōu)化、品牌網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)