第一步:pom.xml文件中引入pinyin4j依赖
com.belerweb
pinyin4j
2.5.0
第二步:新增PinYinUtil工具类
/*
* Copyright (C) 2018 Baidu, Inc. All Rights Reserved.
*/
package test;
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;
/**
* 汉字转换为拼音
* @author Red
*/
public class PinYinUtil {
/**
* 测试main方法
* @param args
*/
public static void main(String[] args) {
System.out.println(toFirstChar("汉字转换为拼音").toUpperCase()); //转为首字母大写
System.out.println(toPinyin("汉字转换为拼音"));
}
/**
* 获取字符串拼音的第一个字母
* @param chinese
* @return
*/
public static String toFirstChar(String chinese){
String pinyinStr = "";
char[] newChar = chinese.toCharArray(); //转为单个字符
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < newChar.length; i++) {
if (newChar[i] > 128) {
try {
pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0].charAt(0);
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
}else{
pinyinStr += newChar[i];
}
}
return pinyinStr;
}
/**
* 汉字转为拼音
* @param chinese
* @return
*/
public static String toPinyin(String chinese){
String pinyinStr = "";
char[] newChar = chinese.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < newChar.length; i++) {
if (newChar[i] > 128) {
try {
pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0];
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
}else{
pinyinStr += newChar[i];
}
}
return pinyinStr;
}
}
第三步:调用PinYinUtil工具类静态方法实现汉字向拼音的转换
PinYinUtil.toPinyin(vo.getName())
延伸阅读:
https://github.com/belerweb/pinyin4j 在github开源项目中可以找到maven中可以引入的最新版本的配置,如下: