java汉字转拼音
一、maven依赖包
<dependency> <groupId>com.belerweb</groupId> <artifactId>pinyin4j</artifactId> <version>2.5.0</version> </dependency>
二、代码
package com.company.project.common.utils; 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.exception.BadHanyuPinyinOutputFormatCombination; public class PinYinUtil { public static void main(String[] args) { //输出:ZHANGSAN System.out.println(toPinyin("张三").toUpperCase()); //输出:zs System.out.println(toFirstChar("张三")); } /** * 汉字转换为拼音首字母 * @param chinese 汉字 * @return */ public static String toFirstChar(String chinese){ String convert = ""; for (int j = 0; j < chinese.length(); j++) { char word = chinese.charAt(j); String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word); if (pinyinArray != null) { convert += pinyinArray[0].charAt(0); } else { convert += word; } } return convert; } /** * 汉字转全拼 * @param chinese 汉字 * @return */ 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(); } } else { pinyinStr += newChar[i]; } } return pinyinStr; } }