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 test {
/**
* 将汉字转换为拼音(带声调)
*/
public static String toPinyinWithTone(String chinese) {
return convertChineseToPinyin(chinese, true, false, false);
}
/**
* 将汉字转换为拼音(不带声调)
*/
public static String toPinyinWithoutTone(String chinese) {
return convertChineseToPinyin(chinese, false, false, false);
}
/**
* 将汉字转换为拼音首字母
*/
public static String toPinyinFirstLetter(String chinese) {
return convertChineseToPinyin(chinese, false, true, false);
}
/**
* 将汉字转换为拼音(首字母大写,不带声调)
*/
public static String toPinyinCapitalized(String chinese) {
return convertChineseToPinyin(chinese, false, false, true);
}
/**
* 汉字转换为拼音的核心方法
*
* @param chinese 中文字符串
* @param withTone 是否带声调
* @param firstLetterOnly 是否只取首字母
* @param capitalized 是否首字母大写
* @return 转换后的拼音字符串
*/
private static String convertChineseToPinyin(String chinese, boolean withTone,
boolean firstLetterOnly, boolean capitalized) {
if (chinese == null || chinese.isEmpty()) {
return "";
}
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
// 设置拼音大小写
format.setCaseType(capitalized ? HanyuPinyinCaseType.UPPERCASE : HanyuPinyinCaseType.LOWERCASE);
// 设置声调格式
format.setToneType(withTone ? HanyuPinyinToneType.WITH_TONE_MARK : HanyuPinyinToneType.WITHOUT_TONE);
// 关键修复:根据是否带声调设置ü的显示方式
format.setVCharType(withTone ? HanyuPinyinVCharType.WITH_U_UNICODE : HanyuPinyinVCharType.WITH_U_AND_COLON);
StringBuilder pinyin = new StringBuilder();
char[] chars = chinese.toCharArray();
for (char c : chars) {
// 如果是汉字
if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
try {
String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
if (pinyinArray != null && pinyinArray.length > 0) {
String py = pinyinArray[0]; // 取第一个拼音
if (firstLetterOnly) {
pinyin.append(py.charAt(0));
} else {
pinyin.append(py);
}
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
// 非汉字直接添加
pinyin.append(c);
}
pinyin.append(" ");
}
return pinyin.toString();
}
// 测试方法
public static void main(String[] args) {
String chinese = "银行行长";
System.out.println("带声调: " + toPinyinWithTone(chinese));
System.out.println("不带声调: " + toPinyinWithoutTone(chinese));
System.out.println("首字母: " + toPinyinFirstLetter(chinese));
System.out.println("首字母大写: " + toPinyinCapitalized(chinese));
}
}