In the project, Hanyu Pinyin is often used, especially the conversion of Chinese characters into Hanyu Pinyin. A common tool is given below.
You must add the Pinyin4j-2.5.0-sources.jar package when you use the program.
ImportNet.sourceforge.pinyin4j.PinyinHelper;ImportNet.sourceforge.pinyin4j.format.HanyuPinyinCaseType;ImportNet.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;ImportNet.sourceforge.pinyin4j.format.HanyuPinyinToneType;ImportNet.sourceforge.pinyin4j.format.HanyuPinyinVCharType;Importnet.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; Public classtopinyinstring {//convert Chinese characters to full spell Public Staticstring Getpingyin (string src) {Char[] T1 =NULL; T1=Src.tochararray (); string[] T2=NewString[t1.length]; Hanyupinyinoutputformat T3=NewHanyupinyinoutputformat (); T3.setcasetype (hanyupinyincasetype.lowercase); //return lowercaseT3.settonetype (Hanyupinyintonetype.without_tone);//return to no toneT3.setvchartype (HANYUPINYINVCHARTYPE.WITH_V);//the character is represented by VString T4 = ""; intT0 =t1.length; Try { for(inti = 0; i < t0; i++) { //determine if the character is Chinese characters if(Java.lang.Character.toString (T1[i]). Matches ("[\\u4e00-\\u9fa5]+")) {//regular expressions that match at least one kanjit2 =Pinyinhelper.tohanyupinyinstringarray (t1[i], T3); T4+ = T2[0]; } ElseT4+=java.lang.Character.toString (T1[i]); } returnT4; } Catch(badhanyupinyinoutputformatcombination E1) {e1.printstacktrace (); } returnT4; } //returns the first letter of Chinese Public Staticstring Getpinyinheadchar (String str) {string convert= ""; for(intj = 0; J < Str.length (); J + +) { CharWord =Str.charat (j); String[] Pinyinarray=Pinyinhelper.tohanyupinyinstringarray (word); if(Pinyinarray! =NULL) {convert+ = Pinyinarray[0].charat (0); } Else{convert+=Word; } } returnconvert; } //To transfer a string to an ASCII code Public Staticstring Getcnascii (String cnstr) {StringBuffer strbuf=NewStringBuffer (); byte[] BGBK =cnstr.getbytes (); for(inti = 0; i < bgbk.length; i++) {strbuf.append (integer.tohexstring (bgbk[i)& 0xFF)); } returnstrbuf.tostring (); } Public Static voidMain (string[] args) {
System.out.println ("Kanji to Hanyu Pinyin:" +getpingyin ("Beautiful Zhongguo, My Hometown"));
SYSTEM.OUT.PRINTLN ("The initials of Chinese characters:" +getpinyinheadchar ("Beautiful Zhongguo, My Hometown"));
System.out.println ("Kanji to ASCII value:" +getcnascii ("Beautiful Zhongguo, My Hometown"));
}}
As shown in the code above, the result of Run as prints is as follows:
java-Kanji converted into Hanyu Pinyin (Pinyin4j-2.5.0-sources.jar)