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.HanyuPinyinVCharType; import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; public class ChineseConvert { private static final HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); static { defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); // 遇到“ü” 显示成V defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V); // 所有输出大写 defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE); } /** * 中文字符串转拼音全写. * * @param resource - 中文字符串 * @return - 拼音全写 */ public static String convertFull(String resource) { return convert(resource, true); } /** * 中文字符串转拼音缩写,取汉字拼音的第一个字母. * * @param resource - 中文字符串 * @return - 拼音全写 */ public static String convertFirstWord(String resource) { return convert(resource, false); } /** * 中文字符串转拼音. * * @param resource - 中文字符串 * @param isFull - 是否全写. true - 全写, false - 缩写 * @return - 拼音字符串 */ public static String convert(String resource, boolean isFull) { StringBuffer buff = new StringBuffer(0); try { char temp; String[] convertArray = null; char[] pinyinArray = resource.toCharArray(); for (int i = 0, j = pinyinArray.length; i < j; i++) { temp = pinyinArray[i]; if (128 < temp) { convertArray = PinyinHelper.toHanyuPinyinStringArray(temp, defaultFormat); if (null != convertArray && convertArray.length > 0) { if (isFull) buff.append(convertArray[0]); else buff.append(convertArray[0].charAt(0)); } } else { buff.append(temp); } } } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } return buff.toString().replaceAll("\\W", "").trim(); } }所需jar包:
pinyin4j.jar
汉字转换成拼音
最新推荐文章于 2024-04-29 14:34:31 发布