java中将你输入的汉字转换为全拼
需要的jar包:pinyin4j-2.5.1.jar
jar包下载链接:https://pan.baidu.com/s/1glHaSGrcnP4IsNXiV3Zh5A
提取码:09bf
package javaTest;
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;
public class GetPingyin {
public static String getPy(String str) {
//定义一个存储输入中文字符串的数组
char[] hz = null;
hz = str.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 (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return pys;
}
// 测试
public static void main(String[] args) {
String str = "伟大的祖国我爱你!";
System.out.println(getPy(str));
}
}
测试图片:
成功完成了哦!!!!!!!!!!!!!!!!!!!!!!!!