packageminyuantec.backupsystem.action;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 classPinyinUtil {/*** 将汉字转换为全拼
*
*@paramsrc
*@returnString*/
private staticString getPinYin(String src) {char[] 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= "";int t0 =t1.length;try{for (int i = 0; i < t0; ++i) {//判断是否为汉字字符
if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {
t2= PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);//将汉字的几种全拼都存到t2数组中
t4 += t2[0];//取出该汉字全拼的第一种读音并连接到字符串t4后
} else{//如果不是汉字字符,直接取出字符并连接到字符串t4后
t4 = t4 +Character.toString(t1[i]);
}
}
}catch(BadHanyuPinyinOutputFormatCombination var8) {
var8.printStackTrace();
}returnt4;
}/*** 中文汉字转成拼音首字母大写
*
*@paramstr
*@returnString*/
public staticString testPinyinInitial(String name){
String pinyinInitial= "";try{char[] charArray =name.toCharArray();
StringBuilder pinyin= newStringBuilder();
HanyuPinyinOutputFormat defaultFormat= newHanyuPinyinOutputFormat();//设置大小写格式
defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);//设置声调格式:
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);for (int i = 0; i < charArray.length; i++) {//匹配中文,非中文转换会转换成null
if (Character.toString(charArray[i]).matches("[\\u4E00-\\u9FA5]+")) {
String[] hanyuPinyinStringArray=PinyinHelper
.toHanyuPinyinStringArray(charArray[i], defaultFormat);if (hanyuPinyinStringArray != null) {
pinyin.append(hanyuPinyinStringArray[0].charAt(0));
}
}
}
pinyinInitial=pinyin.toString();returnpinyinInitial;
}catch(BadHanyuPinyinOutputFormatCombination e) {//TODO: handle exception
}returnpinyinInitial;
}//中文汉字转成ASCII码
public staticString getCnASCII(String cnStr) {
StringBuffer strBuf= newStringBuffer();//将字符串转换成字节序列
byte[] bGBK =cnStr.getBytes();for (int i = 0; i < bGBK.length; i++) {//将每个字符转换成ASCII码
strBuf.append(Integer.toHexString(bGBK[i] & 0xff) + " ");
}returnstrBuf.toString();
}public static voidmain(String[] args) {
String str= "你好世界";
String pinyin=getPinYin(str);
System.out.println(pinyin);
String pinyinInitial=testPinyinInitial(str);
System.out.println(pinyinInitial);
String ascii=getCnASCII(str);
System.out.println(ascii);
}
}