1.引入依赖
<!-- 中文拼音转换 -->
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>
2.工具类代码如下
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;
/**
* 拼音转换工具类
*
* @Description TODO
* @date 2022-07-27 13:58
*/
public class PinYinUtil {
/**
* @param chineseCharacters (字符串 汉字)
* @return 汉字转拼音 其它字符不变
*/
public static String getPinyinToUpperCase(String chineseCharacters) {
HanyuPinyinOutputFormat formart = new HanyuPinyinOutputFormat();
formart.setCaseType(HanyuPinyinCaseType.LOWERCASE);
formart.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
formart.setVCharType(HanyuPinyinVCharType.WITH_V);
char[] arrays = chineseCharacters.trim().toCharArray();
String result = "";
try {
for (int i = 0; i < arrays.length; i++) {
char ti = arrays[i];
if (Character.toString(ti).matches("[\\u4e00-\\u9fa5]")) { //匹配是否是中文
String[] temp = PinyinHelper.toHanyuPinyinStringArray(ti, formart);
//利用Ascii码进行大写转换
char[] cs = temp[0].toCharArray();
cs[0] -= 32;
result += String.valueOf(cs);
} else {
result += ti;
}
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
return result;
}
}