首先导入这个jar包 <!--拼音工具包 --> <dependency> <groupId>com.belerweb</groupId> <artifactId>pinyin4j</artifactId> <version>2.5.0</version> </dependency>
public class ChineseToPinYinUtil { /** * 获取字符串拼音的第一个字母 */ public static String ToFirstChar(String chinese){ String pinyinStr = ""; // 转为单个字符 char[] newChar = chinese.toCharArray(); HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE); defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); for (int i = 0; i < newChar.length; i++) { if (newChar[i] > 128) { try { String[] str = PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat); if(null != str) { pinyinStr += str[0].charAt(0); } } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } }else{ pinyinStr += newChar[i]; } }return pinyinStr; } /** * 汉字转为拼音 */ public static String ToPinyin(String chinese) { String pinyinStr = ""; char[] newChar = chinese.toCharArray(); HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE); defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); for (int i = 0; i < newChar.length; i++) { if (newChar[i] > 128) { try { pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0]; } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } } else { pinyinStr += newChar[i]; } } return pinyinStr; } }