1. 导包 pinyin4j
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>
2. 测试代码
package com.huawei.leetcode.editor.cn;
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;
/**
* @Author T
* @Date 2022/8/16 22:51
* @Version 1.0
*/
public class ChineseTest {
public static void main(String[] args) {
System.out.println(transfer("樱木花道"));
}
/**
* @param original (字符串 汉字)
* @return 汉字转拼音 其它字符不变
*/
public static String transfer(String original) {
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
format.setVCharType(HanyuPinyinVCharType.WITH_V);
char[] arrays = original.trim().toCharArray();
StringBuilder result = new StringBuilder();
try {
for (char ti : arrays) {
// 匹配是否是中文
if (Character.toString(ti).matches("[\\u4e00-\\u9fa5]")) {
String[] temp = PinyinHelper.toHanyuPinyinStringArray(ti, format);
result.append(temp[0]);
} else {
result.append(ti);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result.toString();
}
}