您的位置:首页 > 其它

使用 pinyin4j API 将汉字转换为拼音 (学习笔记)

2018-03-05 11:17 609 查看

1.导入 pinyin4j.jar



2.使用实例

public class PinYin {

/**
* 将汉字转换为全拼
* @param src
* @return
*/
public static String getPinYin(String src){
char[] hz = null;
hz = src.toCharArray();//该方法的作用是返回一个字符数组,该字符数组中存放了当前字符串中的所有字符

String[] py = new String[hz.length];//该数组用来存储

//设置汉子拼音输出的格式
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
format.setVCharType(HanyuPinyinVCharType.WITH_V);

String pys = ""; //存放拼音字符串
int len = hz.length;

try {
for (int i = 0; i < len ; i++ ){
//先判断是否为汉字字符
if(Character.toString(hz[i]).matches("[\\u4E00-\\u9FA5]+")){
//将汉字的几种全拼都存到py数组中
py = PinyinHelper.toHanyuPinyinStringArray(hz[i],format);
//取出改汉字全拼的第一种读音,并存放到字符串pys后
pys += py[0];
}else{
//如果不是汉字字符,间接取出字符并连接到 pys 后
pys += Character.toString(hz[i]);
}
}
} catch (BadHanyuPinyinOutputFormatCombination e){
e.printStackTrace();
}
return pys;
}

/**
* 提取每个汉字的首字母
* @param str
* @return
*/
public static String getPinYinHeadChar(String str){
String convert = "";
for (int i = 0; i < str.length(); i++) {
char word = str.charAt(i);
//提取汉字的首字母
String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
if (pinyinArray != null){
convert += pinyinArray[0].charAt(0);
}else{
convert += word;
}
}
return convert.toUpperCase();
}

/**
* 将字符串转换成ASCII码
*/
public static String getCnASCII(String str){
StringBuffer buf = new StringBuffer();
//将字符串转换成字节序列
byte[] bGBK = str.getBytes();

for (int i = 0; i < bGBK.length; i++) {
//将每个字符转换成ASCII码
buf.append(Integer.toHexString(bGBK[i] & 0xff));
}
return buf.toString();
}

/**
* 测试
*/
public static void main(String[] args) {
String str = "中国梦ChainDream2018";
System.out.println(getPinYin(str));
System.out.println(getPinYinHeadChar(str));
System.out.println(getCnASCII(str));
}
}

3.测试效果




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  pinyin4j