コードコピーは次のとおりです。
net.sourceforge.pinyin4j.pinyinhelperをインポートします。
net.sourceforge.pinyin4j.format.hanyupinyincaseTypeをインポートします。
net.sourceforge.pinyin4j.format.hanyupinyinoutputformatをインポートします。
net.sourceforge.pinyin4j.format.hanyupinyIntoneTypeをインポートします。
net.sourceforge.pinyin4j.format.hanyupinyinvchartypeをインポートします。
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);
string [] t2 = new String [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(character.toString(t1 [i])。一致( "[// u4e00- // u9fa5]+")){
T2 = pinyinhelper.tohanyupinyinstringarray(t1 [i]、t3); //漢字のすべてのスペルをT2アレイに保存します
t4 += t2 [0]; //漢字の最初の発音を取り出して弦のt4に接続した後
} それ以外 {
//それが漢字ではない場合、キャラクターを間接的に抽出して文字列T4に接続した後
t4 += character.toString(t1 [i]);
}
}
} catch(badhanyupinyinoutputformatcombination e){
e.printstacktrace();
}
T4を返します。
}
/**
*各漢字の最初の文字を抽出します
*
* @param str
* @return文字列
*/
public static string getpinyinheadchar(string str){
文字列convert = "";
for(int j = 0; j <str.length(); j ++){
char word = str.charat(j);
//漢字の最初の文字を抽出します
string [] 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();
//文字列をバイトシーケンスに変換します
byte [] 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(getPinyInHeadChar(CNSTR));
System.out.println(getCnaScii(CNSTR));
}
}