声明:本文是对https://www.cnblogs.com/DreamDrive/p/5762078.html的整理,感谢博主分享。
我就是爱音乐~
准备工作:在pom.xml中引入依赖。
<!-- https://mvnrepository.com/artifact/com.belerweb/pinyin4j -->
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.1</version>
</dependency>
工具类:
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;
/**
* 汉字转换为拼音 工具类
*
* 声明:整理优化自https://www.cnblogs.com/DreamDrive/p/5762078.html
*
* @author JustryDeng
* @date 2019/3/18 9:49
*/
public class ChineseToPinyinUtil {
/** (一个)中文 正则表达式 */
private static final String CHINESE_REGEX = "[\u4e00-\u9fa5]";
/**
* 将指定字符串中的中文转为汉语拼音,其余非中文的部分不变
* 注:拼音小写
*
* @param originChinese
* 要转成拼音的中文
* @param abbreviation
* 是否简写 true, 【张三】转换为【zs】
* false, 【张三】转换为【zhangsan】
* @param caseType
* 控制拼音大小写
*
* @return 拼音
* @throws BadHanyuPinyinOutputFormatCombination
* HanyuPinyinOutputFormat格式有误
*/
public static String convertChineseToPinyin(String originChinese,
boolean abbreviation,
HanyuPinyinCaseType caseType)
throws BadHanyuPinyinOutputFormatCombination {
// 将字符串 转换为 字符数组
char[] chineseCharArray = originChinese.trim().toCharArray();
// 设置转换格式
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
// 输出拼音全部小写(默认即为小写)
defaultFormat.setCaseType(caseType);
// 不带声调
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
/*
* 含ü的字有 【女】【吕】【略】【虐】等
*
* WITH_V 设置 【ü】 转换为 【v】 , 如:【女】 转换后为 【nv】
* WITH_U_AND_COLON 设置 【ü】 转换为 【u:】, 如:【女】 转换后为 【nu:】
* WITH_U_UNICODE 设置 【ü】 转换为 【ü】,即:原输出, 如:【女】 转换后为 【nü】
*/
defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
StringBuilder hanYuPinYinResult = new StringBuilder(6);
boolean isChinese;
String tempStr;
for (char cStr : chineseCharArray) {
isChinese = String.valueOf(cStr).matches(CHINESE_REGEX);
// 如果字符是中文,则将中文转为汉语拼音
if (isChinese) {
tempStr = PinyinHelper.toHanyuPinyinStringArray(cStr, defaultFormat)[0];
tempStr = abbreviation ? tempStr.substring(0, 1) : tempStr;
hanYuPinYinResult.append(tempStr);
} else {
// 如果字符不是中文,则不转换
hanYuPinYinResult.append(cStr);
}
}
return hanYuPinYinResult.toString();
}
}
使用测试:
控制台输出: