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;
/**
* @ClassName:PinYinUtil
* @Description:
* @date 2019-08-07 18:37
*/
public class PinYinUtil { /**
/**
* 汉字转换为大写拼音(第一个字母)
* 我就是我->WJSW
*/
public static String toUpFirstPinYin(String hanZhi) {
String pinYin = "";
char[] ch = hanZhi.toCharArray();
for (char item : ch) {
HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
outputFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
String[] stringArray = new String[0];
try {
stringArray = PinyinHelper.toHanyuPinyinStringArray(item, outputFormat);
} catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
badHanyuPinyinOutputFormatCombination.printStackTrace();
}
if (stringArray.length == 0) {
//处理字符不是汉字的情况
pinYin += item;
} else {
pinYin += stringArray[0].toCharArray()[0];
}
}
return pinYin;
}
/**
* 汉字转换为拼音
* 我就是我->wojiushiwo
*/
public static String toPinYin(String hanZhi) throws BadHanyuPinyinOutputFormatCombination {
String pinYin = "";
char[] ch = hanZhi.toCharArray();
for (char item : ch) {
HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
String[] stringArray = PinyinHelper.toHanyuPinyinStringArray(item, outputFormat);
if (stringArray.length == 0) {
//处理字符不是汉字的情况
pinYin += item;
} else {
pinYin += stringArray[0];
}
}
return pinYin;
}
// 解释
public static void test() {
HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
// UPPERCASE:大写 (ZHONG)
// LOWERCASE:小写 (zhong)
outputFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
// WITHOUT_TONE:无音标 (zhong)
// WITH_TONE_NUMBER:1-4数字表示英标 (zhong4)
// WITH_TONE_MARK:直接用音标符(必须WITH_U_UNICODE否则异常) (zhòng)
outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
// WITH_V:用v表示ü (nv)
// WITH_U_AND_COLON:用"u:"表示ü (nu:)
// WITH_U_UNICODE:直接用ü (nü)
outputFormat.setVCharType(HanyuPinyinVCharType.WITH_U_AND_COLON);
}
}
来源:CSDN
作者:秋竹
链接:https://blog.csdn.net/weixin_42605050/article/details/104802702