코드 사본은 다음과 같습니다.
import net.sourceforge.pinyin4j.pinyinhelper;
import net.sourceforge.pinyin4j.format.hanyUpinyIncasetype;
import net.sourceforge.pinyin4j.format.hanyUpinyInoutputFormat;
import net.sourceforge.pinyin4j.format.hanyupinyintoneType;
import net.sourceforge.pinyin4j.format.hanyUpinyInvChartype;
import net.sourceforge.pinyin4j.format.exception.badhanyUpinyInoutputformatcombination;
공개 클래스 pinyin4jutil {
/**
* 한자를 전체 철자로 변환하십시오
*
* @param src
* @return 문자열
*/
public static String getPinyin (String Src) {
char [] t1 = null;
t1 = src.tochararray ();
// system.out.println (t1.length);
문자열 [] t2 = 새 문자열 [t1.length];
// system.out.println (t2.length);
// 중국어 형식을 설정합니다. Pinyin 출력
hanyUpinyInoutputFormat t3 = new hanyUpinyInoutputformat ();
t3.setCaseType (hanyupinyincasetype.lowercase);
t3.settoneType (hanyUpinyIntonEtype.without_tone);
t3.setvchartype (hanyupinyinvchartype.with_v);
문자열 t4 = "";
int t0 = t1.length;
노력하다 {
for (int i = 0; i <t0; i ++) {
// 한자가 될 수 있는지 여부를 결정합니다
// system.out.println (t1 [i]);
if (arribute.tostring (t1 [i]). 일치 ( "[// u4e00-// u9fa5]+") {
t2 = pinyinHelper.ToHanyUpinyInstringArray (T1 [i], T3); // 중국어의 모든 철자를 T2 어레이에 저장하십시오.
T4 += T2 [0]; // 중국어의 첫 발음을 꺼내어 문자열 t4에 연결 한 후
} 또 다른 {
// 중국어가 아닌 경우 문자를 간접적으로 추출하여 문자열에 연결 한 후 T4
t4 += 문자 .toString (t1 [i]);
}
}
} catch (badhanyUpinyInoutputformatcombination e) {
e.printstacktrace ();
}
반환 t4;
}
/**
* 각 중국어의 첫 글자를 추출하십시오
*
* @param str
* @return 문자열
*/
public static String getPinyInbatch Char (String str) {
문자열 convert = "";
for (int j = 0; j <str.length (); j ++) {
char Word = str.charat (j);
// 한자의 첫 글자를 추출합니다
문자열 [] pinyinarray = pinyinHelper.toHanyUpinyInstringArray (Word);
if (pinyinarray! = null) {
convert += pinyinarray [0] .charat (0);
} 또 다른 {
변환 += Word;
}
}
반환 변환;
}
/**
* 문자열을 ASCII 코드로 변환합니다
*
* @param cnstr
* @return 문자열
*/
public static String getCnascii (String Cnstr) {
StringBuffer strbuf = new StringBuffer ();
// 문자열을 바이트 시퀀스로 변환합니다
바이트 [] bgbk = cnstr.getBytes ();
for (int i = 0; i <bgbk.length; i ++) {
// system.out.println (integer.tohexstring (bgbk [i] & 0xff));
// 각 문자를 ASCII 코드로 변환합니다
strbuf.append (integer.tohexstring (bgbk [i] & 0xff));
}
return strbuf.tostring ();
}
public static void main (String [] args) {
문자열 cnstr = "중국";
System.out.println (getpinyin (cnstr));
System.out.println (getPinyInbatchchar (CNSTR));
System.out.println (getcnascii (cnstr));
}
}