import net.sourceforge.pinyin4j.PinyinHelper; 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; /** * 拼音辅助类 * @author tanf * @date 2013-10-10 */ public class PinyinUtil { private static HanyuPinyinOutputFormat PINYIN_FORMAT; static { PINYIN_FORMAT = new HanyuPinyinOutputFormat(); PINYIN_FORMAT.setToneType(HanyuPinyinToneType.WITHOUT_TONE); PINYIN_FORMAT.setVCharType(HanyuPinyinVCharType.WITH_V); } public static String toPinyin(String input) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (c <= 255) { sb.append(c); } else { String pinyin = null; try { String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, PINYIN_FORMAT); pinyin = pinyinArray[0]; } catch (BadHanyuPinyinOutputFormatCombination e) { } catch (NullPointerException e) { // 如果是日文,可能抛出该异常 } if (pinyin != null) { sb.append(pinyin); } } } return sb.toString(); } public static void main(String[] args) { String str = "张三"; String result = toPinyin(str); System.out.println(result); } }
最近下载更多