1 . pom 如下
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>
2.工具类
/**
* 汉字转汉语拼音
*
*/
public static String toHanYuPinYin(String str){
StringBuffer re = new StringBuffer();
try {
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if(c=='区'){
re.append("ou");
}else {
String[] strings = PinyinHelper.toHanyuPinyinStringArray(chars[i], format);
re.append(strings[0]);
}
}
} catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
badHanyuPinyinOutputFormatCombination.printStackTrace();
}
return re.toString();
}