java漢字轉拼音
阿新 • • 發佈:2019-01-04
public class HanzhiToPinyinUtil{ /** * 獲得漢語拼音首字母 * * @param chines 漢字 * @return */ public static String getAlpha(String chines) { String pinyinName = ""; char[] nameChar = chines.toCharArray(); HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE); defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); for (int i = 0; i < nameChar.length; i++) { if (nameChar[i] > 128) { try { pinyinName += PinyinHelper.toHanyuPinyinStringArray( nameChar[i], defaultFormat)[0].charAt(0); } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } } else { pinyinName += nameChar[i]; } } return pinyinName; } /** * 將字串中的中文轉化為拼音,英文字元不變 * * @param inputString * 漢字 * @return */ public static String getPingYin(String inputString) { HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat(); format.setCaseType(HanyuPinyinCaseType.LOWERCASE); format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); format.setVCharType(HanyuPinyinVCharType.WITH_V); String output = ""; if (inputString != null && inputString.length() > 0 && !"null".equals(inputString)) { char[] input = inputString.trim().toCharArray(); try { for (int i = 0; i < input.length; i++) { if (java.lang.Character.toString(input[i]).matches( "[\\u4E00-\\u9FA5]+")) { String[] temp = PinyinHelper.toHanyuPinyinStringArray( input[i], format); output += temp[0]; } else output += java.lang.Character.toString(input[i]); } } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } } else { return "*"; } return output; } /** * 漢字轉換位漢語拼音首字母,英文字元不變 * * @param chines * 漢字 * @return 拼音 */ public static String converterToFirstSpell(String chines) { String pinyinName = ""; char[] nameChar = chines.toCharArray(); HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE); defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); for (int i = 0; i < nameChar.length; i++) { if (nameChar[i] > 128) { try { pinyinName += PinyinHelper.toHanyuPinyinStringArray( nameChar[i], defaultFormat)[0].charAt(0); } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } } else { pinyinName += nameChar[i]; } } return pinyinName; } /** * 測試 * [功能說明] * * @param args */ public static void main (String[] args) { System.out.println(getAlpha("測試")); } }