public class ChineseAndPinyinUtils {
private ChineseAndPinyinUtils() {}
/**
* @param chinese (字符串 汉字)
* @return 汉字转拼音 其它字符不变
*/
public static String getPinyin(String chinese){
HanyuPinyinOutputFormat formart = new HanyuPinyinOutputFormat();
//拼音输出默认为小写,公共方法不做限制
//下面设置输出拼音为大写
//formart.setCaseType(HanyuPinyinCaseType.UPPERCASE);
//拼音输出不带声调,否则带声调的字母乱码
formart.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
//字母'ü' 输出为 'v',否则也是乱码
formart.setVCharType(HanyuPinyinVCharType.WITH_V);
char[] arrays = chinese.trim().toCharArray();
String result = "";
try {
for (int i=0;i<arrays.length;i++) {
char ti = arrays[i];
if(Character.toString(ti).matches("[\\u4e00-\\u9fa5]")){ //匹配是否是中文
String[] temp = PinyinHelper.toHanyuPinyinStringArray(ti,formart);
result += temp[0];
}else{
result += ti;
}
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
return result;
}
}
字符串转成拼音
于 2021-09-13 16:26:38 首次发布
关键词由CSDN通过智能技术生成