汉字转拼音工具类

1、首先需要引入汉语转拼音的jar包 pinyin4j-2.5.0.jar

2、代码

    publicclass PinyinUtil {

         publicstatic String converterToSpell(String chines) {

                   StringBuffer pinyinName = new StringBuffer();

                   char[] nameChar = chines.toCharArray();

                   HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();

                   defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);

                   defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 不带音标

                   defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V);

                   for (int i = 0; i < nameChar.length; i++) {

                            if (nameChar[i] > 128) {

                                     try {

                                               String strs[] = PinyinHelper.toHanyuPinyinStringArray(

                                                                 nameChar[i], defaultFormat);

                                               if (strs != null) {

                                                        pinyinName.append(strs[0]);

                                               }

                                     } catch (BadHanyuPinyinOutputFormatCombination e) {

                                               e.printStackTrace();

                                     }

                            } else {

                                     pinyinName.append(nameChar[i]);

                            }

                   }

                   String pinyin = pinyinName.toString().trim();

                   return pinyin;

         }

}

你可能感兴趣的:(汉字转拼音工具类)