中文轉換英文,首先引入pom文件java
<dependency> <groupId>com.belerweb</groupId> <artifactId>pinyin4j</artifactId> <version>2.5.0</version> </dependency>
工具類:web
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; /** * @Author: zhukai * @Description: 將姓名漢字轉換成拼音 * @Date: create in 2017/8/1. */ public class Pinyin4jUtil { // 名字長度 private static int NAME_LENGTH = 3; // 將漢字轉換爲全拼 public static String getPingYin(String src) { char[] name = src.toCharArray(); String[] newName = new String[name.length]; HanyuPinyinOutputFormat pyFormat = new HanyuPinyinOutputFormat(); pyFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE); pyFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); pyFormat.setVCharType(HanyuPinyinVCharType.WITH_V); String account = ""; int length = name.length; try { // 名字大於等於3個字的時候,姓取全稱,名取首字母。 if(length>=NAME_LENGTH){ for (int i = 0; i < length; i++) { // 截取姓 if(i==0){ // 判斷是否爲漢字字符 if (Character.toString(name[i]).matches("[\\u4E00-\\u9FA5]+")) { newName = PinyinHelper.toHanyuPinyinStringArray(name[i], pyFormat); account += newName[0]; } else account += Character.toString(name[i]); }else{ account += getPinYinHeadChar(Character.toString(name[i])); } } }else{ // 只有2個字的名字,帳號是名字的拼音全稱 for (int i = 0; i < length; i++) { // 判斷是否爲漢字字符 if (Character.toString(name[i]).matches("[\\u4E00-\\u9FA5]+")) { newName = PinyinHelper.toHanyuPinyinStringArray(name[i], pyFormat); account += newName[0]; } else account += Character.toString(name[i]); } } return account; } catch (BadHanyuPinyinOutputFormatCombination e1) { e1.printStackTrace(); } return account; } // 返回中文的首字母 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; } }