java 實現漢字轉拼音

來源:互聯網
上載者:User

用到了pinyin4j-2.5.0.jar這樣一個jar包;具體實現代碼如下:import net.sourceforge.pinyin4j.PinyinHelper;import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;public class HanziToPinyin {/*** 將漢字轉換為全拼* * @param src* @return String*/public static String getPinYin(String src) {char[] t1 = null;t1 = src.toCharArray();// System.out.println(t1.length);String[] t2 = new String[t1.length];// System.out.println(t2.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++) {// 判斷是否為漢字字元// System.out.println(t1[i]);if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);// 將漢字的幾種全拼都存到t2數組中t4 += t2[0];// 取出該漢字全拼的第一種讀音並串連到字串t4後} else {// 如果不是漢字字元,直接取出字元並串連到字串t4後t4 += Character.toString(t1[i]);}}} catch (BadHanyuPinyinOutputFormatCombination e) {// TODO Auto-generated catch blocke.printStackTrace();}return t4.toUpperCase();}/*** 提取每個漢字的首字母* * @param str* @return String*/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);if (pinyinArray != null) {convert += pinyinArray[0].charAt(0);} else {convert += word;}}return convert.toUpperCase();}/*** 將字串轉換成ASCII碼* * @param cnStr* @return String*/public static String getCnASCII(String cnStr) {StringBuffer strBuf = new StringBuffer();// 將字串轉換成位元組序列byte[] bGBK = cnStr.getBytes();for (int i = 0; i < bGBK.length; i++) {// System.out.println(Integer.toHexString(bGBK[i] & 0xff));// 將每個字元轉換成ASCII碼strBuf.append(Integer.toHexString(bGBK[i] & 0xff));}return strBuf.toString();}}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.