有時我們需要獲取文字的拼音,根據首字母排序,如城市,姓名等,此處給出兩種方法。第一種需要引入第三方jar包,但是兼容GBK和UTF-8的編碼。第二種不用引包,但是隻在GBK下生效。
我之前在新浪博客中也發過博文,具體可見地址
Java中獲取中文首字母
這兩種方法都是參考自網絡,此處給出地址
地址1
地址2
地址3
以下爲方法1源碼
jar包爲pinyin4j,請百度下載
public class PinYin {
public static String getPingYin(String src) {
char[] t1 = null;
t1 = src.toCharArray();
String[] t2 = new String[t1.length];
HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
t3.setVCharType(HanyuPinyinVCharType.WITH_V);
String t4 = "";
int t0 = t1.length;
try {
for (int i = 0; i < t0; i++) {
if (java.lang.Character.toString(t1[i]).matches(
"[\\u4E00-\\u9FA5]+")) {
t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);
t4 += t2[0];
} else {
t4 += java.lang.Character.toString(t1[i]);
}
}
return t4;
} catch (Exception e1) {
e1.printStackTrace();
}
return t4;
}
public static String getPinYinHeadChar(String str) {
String convert = "";
for (int j = 0; j < str.length(); j++) {
char word = str.charAt(j);
String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word,
new HanyuPinyinOutputFormat());
if (pinyinArray != null) {
convert += pinyinArray[0].charAt(0);
} else {
convert += word;
}
}
return convert;
}
public static String getCnASCII(String cnStr) {
StringBuffer strBuf = new StringBuffer();
byte[] bGBK = cnStr.getBytes();
for (int i = 0; i < bGBK.length; i++) {
strBuf.append(Integer.toHexString(bGBK[i] & 0xff));
}
return strBuf.toString();
}
public static void main(String[] args) {
String cnStr ="我去年買了個表";
System.out.println(getPingYin(cnStr));
System.out.println(getPinYinHeadChar(cnStr));
}
}
方法2的源碼
“`
public class PinYin2 {
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++) {
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();
}
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;
}
public static void main(String args[]) {
System.out.println(PinYin2.getFirstLetter("我去年買了個表"));
}```