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 classPinyin {/*** Get full spell * *@paramsrc *@return */ Public Staticstring Getpingyin (string src) {Char[] T1 =NULL; T1=Src.tochararray (); string[] T2=NewString[t1.length]; Hanyupinyinoutputformat T3=NewHanyupinyinoutputformat (); T3.setcasetype (hanyupinyincasetype.lowercase); T3.settonetype (Hanyupinyintonetype.without_tone); T3.setvchartype (HANYUPINYINVCHARTYPE.WITH_V); String 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]+") ) {T2=Pinyinhelper.tohanyupinyinstringarray (t1[i], T3); T4+ = T2[0]; } Else{T4+=java.lang.Character.toString (T1[i]); } } returnT4; } Catch(badhanyupinyinoutputformatcombination E1) {e1.printstacktrace (); } returnT4; } /*** Get Chinese initials * *@paramSTR *@return */ 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; } /*** Transfer string to ASCII code * *@paramCnstr *@return */ Public Staticstring Getcnascii (String cnstr) {StringBuffer strbuf=NewStringBuffer (); byte[] BGBK =cnstr.getbytes (); for(inti = 0; i < bgbk.length; i++) { //System.out.println (integer.tohexstring (Bgbk[i]&0xff));Strbuf.append (Integer.tohexstring (bgbk[i) & 0xFF)); } returnstrbuf.tostring (); } Public Static voidMain (string[] args) {String cnstr= "Ling"; System.out.println (Getpingyin (cnstr)); System.out.println (Getpinyinheadchar (cnstr)); }}
JAR file Required: Pinyin4j-2.5.0.jar
Java gets full spelling and initials based on Chinese characters