需要jar:pinyin4j
下载地址为:链接:http://pan.baidu.com/s/1geYOpxh 密码:am4r
public class Test {
public static String getPingYin(String str) throws Exception {
char[] str1 = null;
str1 = str.toCharArray();
String[] str2 = new String[str1.length];
HanyuPinyinOutputFormat str3 = new HanyuPinyinOutputFormat();
t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
t3.setVCharType(HanyuPinyinVCharType.WITH_V);
String str4 = "";
int str0 = str1.length;
for (int i = 0; i < t0; i++) {
// 判断能否为汉字?
if (Character.toString(str1[i]).matches("[\\u4E00-\\u9FA5]+")) {
str2 = PinyinHelper.toHanyuPinyinStringArray(str1[i], t3);// 将汉字的几种全拼都存到str2数组?
str4 += str2[0];// 取出该汉字全拼的第一种读音并连接到字符串t4?
} else {
// 如果不是汉字字符,间接取出字符并连接到字符串str4?
str4 += Character.toString(str1[i]);
}
}
return str4;
}
public static void main(String[] args) throws Exception {
System.out.println(getPingYin("悟空传"));
}
}