源代码下载地址:http://www.zuidaima.com/share/1550463764974592.htm
利用Pinyin4j把中文转换为拼音:
package com.zuidaima; 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 www.zuidaima.com * @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); } }
时间: 2024-10-09 23:43:59