汉字转拼英——简单实现
依赖
<dependency><groupId>com.belerweb</groupId><artifactId>pinyin4j</artifactId><version>2.5.0</version>
</dependency>
汉字转拼音方式1:
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 PinYinUtil {public static void main(String[] args) {System.out.println(getPinyin("中国红123")); //--zhongguohong123}/*** @param china (字符串 汉字)* @return 汉字转拼音 其它字符不变*/public static String getPinyin(String china){HanyuPinyinOutputFormat formart = new HanyuPinyinOutputFormat();formart.setCaseType(HanyuPinyinCaseType.LOWERCASE);formart.setToneType(HanyuPinyinToneType.WITHOUT_TONE);formart.setVCharType(HanyuPinyinVCharType.WITH_V);char[] arrays = china.trim().toCharArray();String result = "";try {for (int i=0;i<arrays.length;i++) {char ti = arrays[i];if(Character.toString(ti).matches("[\\u4e00-\\u9fa5]")){ //匹配是否是中文String[] temp = PinyinHelper.toHanyuPinyinStringArray(ti,formart);result += temp[0];}else{result += ti;}}} catch (BadHanyuPinyinOutputFormatCombination e) {e.printStackTrace();}return result;}
}
汉字转拼音方式2
/**
* 获取汉字拼音的方法。如: 张三 --> zhangsan
* 说明:暂时解决不了多音字的问题,只能使用取多音字的第一个音的方案
*
* @param hanzi 汉子字符串
* @return 汉字拼音; 如果都转换失败,那么返回null
* 43
*/
public static String getHanziPinYin(String hanzi) {String result = null;if (null != hanzi && !"".equals(hanzi)) {char[] charArray = hanzi.toCharArray();StringBuffer sb = new StringBuffer();for (char ch : charArray) {if (Character.toString(ch).matches("[\\u4E00-\\u9FA5]+")) {// 逐个汉字进行转换, 每个汉字返回值为一个String数组(因为有多音字)String[] stringArray = PinyinHelper.toHanyuPinyinStringArray(ch);if (null != stringArray) {// 把第几声这个数字给去掉sb.append(stringArray[0].replaceAll("\\d", ""));}} else {sb.append(ch);}}if (sb.length() > 0) {result = sb.toString();}}return result;
}