java中文转全拼工具类分享
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 pinyin4jutil {
/**
* 将汉字转换为全拼
*
* @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);
// 设置汉字拼音输出的格式
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++) {
// 判断能否为汉字字符
// system.out.println(t1[i]);
if (character.tostring(t1[i]).matches("[\\u4e00-\\u9fa5]+")) {
t2 = pinyinhelper.tohanyupinyinstringarray(t1[i], t3);// 将汉字的几种全拼都存到t2数组中
t4 += t2[0];// 取出该汉字全拼的第一种读音并连接到字符串t4后
} else {
// 如果不是汉字字符,间接取出字符并连接到字符串t4后
t4 += character.tostring(t1[i]);
}
}
} catch (badhanyupinyinoutputformatcombination e) {
e.printstacktrace();
}
return t4;
}
/**
* 提取每个汉字的首字母
*
* @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);
// 提取汉字的首字母
string[] pinyinarray = pinyinhelper.tohanyupinyinstringarray(word);
if (pinyinarray != null) {
convert += pinyinarray[0].charat(0);
} else {
convert += word;
}
}
return convert;
}
/**
* 将字符串转换成ascii码
*
* @param cnstr
* @return string
*/
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) {
string cnstr = "中国";
system.out.println(getpinyin(cnstr));
system.out.println(getpinyinheadchar(cnstr));
system.out.println(getcnascii(cnstr));
}
}
下一篇: MySQL子查询用法实例分析