@Slf4j
public class PingYinUtils {
public static String tranHeadPingYin(String hanzi){
if(StringUtils.isBlank(hanzi)) throw new ProjectException(DishEnum.CREATE_FAIL);
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
format.setVCharType(HanyuPinyinVCharType.WITH_U_AND_COLON);
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
char[] hanYuArr = hanzi.trim().toCharArray();
String[][] pinYin = new String[hanYuArr.length][];
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[i]=pys;
} else {
pinYin[i]=new String[1];
pinYin[i][0]=hanYuArr[i]+"";
}
}
} catch (Exception e){
log.error("新增菜品时,自动生成编码出错,错误信息为{}",e.getMessage());
throw new ProjectException(DishEnum.CREATE_FAIL);
}
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < pinYin.length; i++) {
String substring = pinYin[i][0].substring(0, 1);
stringBuilder.append(substring);
}
return stringBuilder.toString();
}
public static void main(String[] args) {
String test = tranHeadPingYin("麻辣香锅");
String test1 = tranHeadPingYin("肥肥是_zhu");
System.out.println(test);
System.out.println(test1);
}
}
<!--拼音4j-->
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>