汉字转换成拼音工具类:
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 }