[springboot]漢字のピンイン(繁体字を含む)
2196 ワード
pom.xml
com.belerweb
pinyin4j
2.5.0
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 static String getAllPinyin(String hanzi) {
//
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
/**
*
* LOWERCASE:
* UPPERCASE:
*/
format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
/**
*
* WITH_TONE_MARK: ( WITH_U_UNICODE, )
* WITH_TONE_NUMBER:1-4
* WITHOUT_TONE:
*/
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
/**
* ü
* WITH_V: v ü
* WITH_U_AND_COLON: "u:" ü
* WITH_U_UNICODE: ü
*/
format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
char[] hanYuArr = hanzi.trim().toCharArray();
StringBuilder pinYin = new StringBuilder();
try {
for (int i = 0, len = hanYuArr.length; i < len; i++) {
//
if (Character.toString(hanYuArr[i]).matches("[\\u4E00-\\u9FA5]+")) {
// , ,
String[] pys = PinyinHelper.toHanyuPinyinStringArray(hanYuArr[i], format);
pinYin.append(pys[0]).append(" ");
} else {
pinYin.append(hanYuArr[i]).append(" ");
}
}
} catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
badHanyuPinyinOutputFormatCombination.printStackTrace();
}
return pinYin.toString();
}
この関数を直接呼び出せばいい