pom.xml进行配置
<!--Pinyin -->
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.1</version>
</dependency>
package com.yoyowang.framework.utils;
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.exception.BadHanyuPinyinOutputFormatCombination;
public class HanyupinyinUtil {
/**
* @Description 中文转拼音,帕斯卡命名法,每个首字母大写
*
* @param chinese 中文字符
*
* @return String 帕斯卡命名法的拼音
*
*/
public static String getPascalString(String chinese) {
String pascalSpell = "";// 返回的拼音
try {
char[] cl_chars = chinese.trim().toCharArray();
// 大写样式
HanyuPinyinOutputFormat upperFormat = new HanyuPinyinOutputFormat();
upperFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);// 大写
upperFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 不带声调
// 小写样式
HanyuPinyinOutputFormat lowerFormat = new HanyuPinyinOutputFormat();
lowerFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);// 小写
lowerFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 不带声调
for (int i = 0; i < cl_chars.length; i++) {
String str = String.valueOf(cl_chars[i]);
if (str.matches("[\u4e00-\u9fa5]+")) {// 如果字符是中文,则将中文转为汉语拼音,并取第一个字母大写,其他字母小写
pascalSpell += PinyinHelper.toHanyuPinyinStringArray(cl_chars[i], upperFormat)[0].substring(0, 1);
pascalSpell += PinyinHelper.toHanyuPinyinStringArray(cl_chars[i], lowerFormat)[0].substring(1);
} else if (str.matches("[0-9]+")) {// 如果字符是数字,取数字
pascalSpell += cl_chars[i];
} else if (str.matches("[a-zA-Z]+")) {// 如果字符是字母,取字母
pascalSpell += cl_chars[i];
} else {// 否则不转换
pascalSpell += cl_chars[i];//如果是标点符号的话,带着
}
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
System.out.println("字符不能转成汉语拼音");
}
return pascalSpell;
}
public static void main(String[] args) {
System.out.println(getPascalString("嗯哼"));
}
}