Java Chinese characters into pinyin implementation code
- 2020-04-01 02:23:38
- OfStack
1. Demonstration:
Welcome to Beijing
Print out pinyin: bei jing huan ying ni
Two: import the dependent jar:
(link: http://xiazai.jb51.net/201310/yuanma/pinyin4j-2.5.0 (jb51.net). Rar)
Three: code writing
public static String getPinYin(String src) {
char[] t1 = null;
t1 = src.toCharArray();
// System.out.println(t1.length);
String[] t2 = new String[t1.length];
// System.out.println(t2.length);
//Format the output of Chinese pinyin & NBSP;
HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
t3.setVCharType(HanyuPinyinVCharType.WITH_V);
String t4 = "";
int t0 = t1.length;
try {
for (int i =0; i < t0; i++) {
//Judge whether it can be a Chinese character & NBSP;
// System.out.println(t1[i]);
if (Character.toString(t1[i]).matches("[\u4E00-\u9FA5]+")) {
t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);//Store the complete spelling of Chinese characters in a t2 array
t4 += t2[0]+" ";//Take the first pronunciation of the Chinese character and connect it to the string t4
} else {
//If it is not a hanzi character, indirectly extract the character and connect it to the string t4
t4 += Character.toString(t1[i]);
}
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
return t4;
}
On such a Chinese character conversion pinyin program done, is not very magical ah.