The code is as follows:
The following are the referenced contents:
Package Com.example.pinyin.demo2;
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;
public class Pinyin {
/**
* Convert Chinese characters to full spelling
* @param src
* @return String
*/
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 phonetic output of Chinese characters
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++) {
Determine if the character is Chinese characters
System.out.println (T1[i]);
if (character.tostring (T1[i]). Matches ("[//u4e00-//u9fa5]+")) {
T2 = Pinyinhelper.tohanyupinyinstringarray (t1[i], T3)//Save a few of the Chinese characters to the T2 array
T4 + + t2[0];//to remove the first pronunciation of the Chinese characters and connect to the string T4
} else {
If it is not a kanji character, remove the character directly and connect to the string T4
T4 + + character.tostring (T1[i]);
}
Source
catch (Badhanyupinyinoutputformatcombination e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
return t4;
}
/**
* Extract the first letter of each Chinese character
* @param str
* @return String
*/
public static string Getpinyinheadchar (String str) {
String convert = "";
for (int j = 0; J < Str.length (); j + +) {
Char word = Str.charat (j);
Extract the first letter of Chinese characters
string[] Pinyinarray = Pinyinhelper.tohanyupinyinstringarray (word);
if (Pinyinarray!= null) {
Convert + + pinyinarray[0].charat (0);
} else {
Convert + + word;
}
}
return convert;
}
/**
* Convert string to ASCII code
* @param cnstr
* @return String
*/
public static string Getcnascii (String cnstr) {
StringBuffer strbuf = new StringBuffer ();
Converts a string into a byte sequence
byte[] BGBK = Cnstr.getbytes ();
for (int i = 0; i < bgbk.length; i++) {
System.out.println (Integer.tohexstring (bgbk[i) & 0xff));
Converts each character into an ASCII code
Strbuf.append (Integer.tohexstring (bgbk[i) & 0xff));
}
return strbuf.tostring ();
}
public static void Main (string[] args) {
String cnstr = "People's Republic of China";
System.out.println (Getpinyin (cnstr));
System.out.println (Getpinyinheadchar (cnstr));
System.out.println (Getcnascii (cnstr));
}
}
Note to the reader: A component package Pinyin4j.jar is used in the program. Exam big-Computer Second class examination