代码
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;
public class PyUtil {
private static String getCharacterPinYin(char c) throws BadHanyuPinyinOutputFormatCombination{
HanyuPinyinOutputFormat format= new HanyuPinyinOutputFormat();
format.setToneType(HanyuPinyinToneType.WITH_TONE_MARK);
format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
String[] pinyin = null;
try {
pinyin = PinyinHelper.toHanyuPinyinStringArray(c, format);
} catch(BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
// 如果c不是汉字,toHanyuPinyinStringArray会返回null
if(pinyin == null) return null;
// 只取一个发音,如果是多音字,仅取第一个发音
return pinyin[0];
}
public static String getStringPinyin(String str) {
HanyuPinyinOutputFormat format= new HanyuPinyinOutputFormat();
format.setToneType(HanyuPinyinToneType.WITH_TONE_MARK);
format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
String[] pinyinArray = null;
try {
StringBuilder sb = new StringBuilder();
String tempPinyin = null;
for(int i = 0; i < str.length(); ++i)
{
tempPinyin =getCharacterPinYin(str.charAt(i));
if (sb.length() > 0) {
sb.append(" ");
}
if(tempPinyin == null) {
// 如果str.charAt(i)非汉字,则保持原样
sb.append(str.charAt(i));
}
else {
sb.append(tempPinyin);
}
}
return sb.toString();
} catch(BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
return "";
}
}
}
测试代码
public static void main(String[] args) {
String temp = PyUtil.getStringPinyin("唐贏");
System.out.println(temp);
}
执行效果