compile "com.github.stuxuhai:jpinyin:1.1.8"
測試代碼:
import com.github.stuxuhai.jpinyin.ChineseHelper; import com.github.stuxuhai.jpinyin.PinyinFormat; import com.github.stuxuhai.jpinyin.PinyinHelper; public class ChangeToPinYinJP { /** * 轉換為有聲調的拼音字符串 * @param pinYinStr 漢字 * @return 有聲調的拼音字符串 */ public String changeToMarkPinYin(String pinYinStr){ String tempStr = null; try { tempStr = PinyinHelper.convertToPinyinString(pinYinStr, " ", PinyinFormat.WITH_TONE_MARK); } catch (Exception e) { e.printStackTrace(); } return tempStr; } /** * 轉換為數字聲調字符串 * @param pinYinStr 需轉換的漢字 * @return 轉換完成的拼音字符串 */ public String changeToNumberPinYin(String pinYinStr){ String tempStr = null; try { tempStr = PinyinHelper.convertToPinyinString(pinYinStr, " ", PinyinFormat.WITH_TONE_NUMBER); } catch (Exception e) { e.printStackTrace(); } return tempStr; } /** * 轉換為不帶音調的拼音字符串 * @param pinYinStr 需轉換的漢字 * @return 拼音字符串 */ public String changeToTonePinYin(String pinYinStr){ String tempStr = null; try { tempStr = PinyinHelper.convertToPinyinString(pinYinStr, " ", PinyinFormat.WITHOUT_TONE); } catch (Exception e) { e.printStackTrace(); } return tempStr; } /** * 轉換為每個漢字對應拼音首字母字符串 * @param pinYinStr 需轉換的漢字 * @return 拼音字符串 */ public String changeToGetShortPinYin(String pinYinStr){ String tempStr = null; try { tempStr = PinyinHelper.getShortPinyin(pinYinStr); } catch (Exception e) { e.printStackTrace(); } return tempStr; } /** * 檢查漢字是否為多音字 * @param pinYinStr 需檢查的漢字 * @return true 多音字,false 不是多音字 */ public boolean checkPinYin(char pinYinStr){ boolean check = false; try { check = PinyinHelper.hasMultiPinyin(pinYinStr); } catch (Exception e) { e.printStackTrace(); } return check; } /** * 簡體轉換為繁體 * @param pinYinStr * @return */ public String changeToTraditional(String pinYinStr){ String tempStr = null; try { tempStr = ChineseHelper.convertToTraditionalChinese(pinYinStr); } catch (Exception e) { e.printStackTrace(); } return tempStr; } /** * 繁體轉換為簡體 * @param pinYinSt * @return */ public String changeToSimplified(String pinYinSt){ String tempStr = null; try { tempStr = ChineseHelper.convertToSimplifiedChinese(pinYinSt); } catch (Exception e) { e.printStackTrace(); } return tempStr; } public static void main(String[] args) { String str = "鄭州市"; ChangeToPinYinJP jp = new ChangeToPinYinJP(); System.out.println(jp.changeToMarkPinYin(str)); System.out.println(jp.changeToTonePinYin(str)); //有空格 System.out.println(jp.changeToSimplified(str)); System.out.println(jp.checkPinYin('重')); } }
