作者:cndz 围观群众:670 更新于 标签:java工具类汉字转拼音工具类
将汉字转为拼音。支持对字母方式(小写、大写、首字母大写),拼音间隔(无、空格、下划线),是否带音调(是、否)多方面设置。效果图如下。
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.1</version>
</dependency>
package top.jhone.common.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.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang3.StringUtils;
import top.jhone.common.enums.admin.YesOrNoEnum;
/**
* @author:zzy
* @date:Created in 2023/4/1 10:56
* @modified By:zzy
*/
public class PinYinFormatUtil {
/**
* @param chinese 待转换文字
* @param letterType 字符方式 0全部小写,1全部大写,2首字母大写
* @param letterBlank 拼音间隔 0无,1空格,2下划线
* @param letterTone 是否待声调 0否 1是
* @return
*/
public static String getPinYin(String chinese, String letterType, String letterBlank, String letterTone) {
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
/* 设置转换后拼音的大小写
UPPERCASE:大写 (ZHONG)
LOWERCASE:小写 (zhong)
*/
if(StringUtils.equals(letterType,"0") || StringUtils.equals(letterType,"2")){
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
}else{
format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
}
/* 设置转换后拼音是否输出拼接音调
WITHOUT_TONE:无音标 (zhong)
WITH_TONE_NUMBER:1-4数字表示英标 (zhong4)
WITH_TONE_MARK:直接用音标符(必须WITH_U_UNICODE否则异常) (zhòng)
*/
if (StringUtils.equals(YesOrNoEnum.YES.getCode(), letterTone)) {
format.setToneType(HanyuPinyinToneType.WITH_TONE_MARK);
} else {
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
}
String blank = "";
if (StringUtils.equals("1", letterBlank)) {
blank = " ";
} else if (StringUtils.equals("2", letterBlank)) {
blank = "_";
}
/* 设置转换后拼音是否输出韵母
WITH_V:用v表示ü (nv)
WITH_U_AND_COLON:用"u:"表示ü (nu:)
WITH_U_UNICODE:直接用ü (nü)
*/
format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
StringBuilder sb = new StringBuilder();
char[] arr = chinese.trim().toCharArray();
try {
for (char c : arr) {
if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
//toHanyuPinyinStringArray有个容错判断 如果传入的不是汉字,就不能转换成拼音,那么直接返回null可以用正则表达式判断是否是中文,Character.toString(input[i]).matches("[\\u4E00-\\u9FA5]+")
String[] temp = PinyinHelper.toHanyuPinyinStringArray(c, format);
if(StringUtils.equals("2",letterType)){
sb.append(blank + firstLetterName(temp[0]));
}else{
sb.append(blank + temp[0]);
}
continue;
}
sb.append(blank +c);
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
throw new IllegalArgumentException("文字转拼音失败");
}
String resultStr = sb.toString();
if(resultStr.startsWith(" ") || resultStr.startsWith("_")){
return resultStr.substring(1);
}
return resultStr;
}
public static String firstLetterName(String name) {
name = name.substring(0, 1).toUpperCase() + name.substring(1);
return name;
}
}