漢字轉換成拼音工具類:
1 import net.sourceforge.pinyin4j.PinyinHelper; 2 import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; 3 import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; 4 import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; 5 import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType; 6 import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; 7 8 public class PinyinUtils { 9 /** 10 * 將漢字轉換為全拼 11 * 12 * @param src 13 * @return String 14 */ 15 public static String getPinYin(String src) { 16 char[] t1 = null; 17 t1 = src.toCharArray(); 18 String[] t2 = new String[t1.length]; 19 // 設置漢字拼音輸出的格式 20 HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat(); 21 t3.setCaseType(HanyuPinyinCaseType.LOWERCASE); 22 t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE); 23 t3.setVCharType(HanyuPinyinVCharType.WITH_V); 24 String t4 = ""; 25 int t0 = t1.length; 26 try { 27 for (int i = 0; i < t0; i++) { 28 // 判斷是否為漢字字符 29 if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) { 30 t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);// 將漢字的幾種全拼都存到t2數組中 31 t4 += t2[0];// 取出該漢字全拼的第一種讀音並連接到字符串t4后 32 } else { 33 // 如果不是漢字字符,直接取出字符並連接到字符串t4后 34 t4 += Character.toString(t1[i]); 35 } 36 } 37 } catch (BadHanyuPinyinOutputFormatCombination e) { 38 // TODO Auto-generated catch block 39 e.printStackTrace(); 40 } 41 return t4; 42 } 43 44 /** 45 * 提取每個漢字的首字母 46 * 47 * @param str 48 * @return String 49 */ 50 public static String getPinYinHeadChar(String str) { 51 String convert = ""; 52 for (int j = 0; j < str.length(); j++) { 53 char word = str.charAt(j); 54 // 提取漢字的首字母 55 String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word); 56 if (pinyinArray != null) { 57 convert += pinyinArray[0].charAt(0); 58 } else { 59 convert += word; 60 } 61 } 62 return convert; 63 } 64 65 /** 66 * 將字符串轉換成ASCII碼 67 * 68 * @param cnStr 69 * @return String 70 */ 71 public static String getCnASCII(String cnStr) { 72 StringBuffer strBuf = new StringBuffer(); 73 // 將字符串轉換成字節序列 74 byte[] bGBK = cnStr.getBytes(); 75 for (int i = 0; i < bGBK.length; i++) { 76 // 將每個字符轉換成ASCII碼 77 strBuf.append(Integer.toHexString(bGBK[i] & 0xff) + " "); 78 } 79 return strBuf.toString(); 80 } 81 82 }