java 汉字转拼音

1.pom文件


    com.belerweb
    pinyin4j
    2.5.1

2.java 代码

/**
	 * 正则去掉所有字符操作
	 * @param chines
	 * @return
	 */
	public static String cleanChar(String chines) {
		chines = chines.replaceAll("[\\p{Punct}\\p{Space}]+", "");
		// 正则表达式去掉所有中文的特殊符号
		String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}<>《》【】‘;:”“’。,、?]";
		Pattern pattern = Pattern.compile(regEx);
		Matcher matcher = pattern.matcher(chines);
		chines = matcher.replaceAll("").trim();
		return chines;
	}
	
	/**
	 * 获取汉字全拼小写
	 * @param chines
	 * @return
	 */
	public static String converterToAllSpell(String chines) {
		chines = cleanChar(chines);
		String pinyinName = "";
		char[] nameChar = chines.toCharArray();
		HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
		defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		for (int i = 0; i < nameChar.length; i++) {
			if (nameChar[i] > 128) {
				try {
					pinyinName += PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[0];
				} catch (BadHanyuPinyinOutputFormatCombination e) {
					//e.printStackTrace();
				}catch(java.lang.ArrayIndexOutOfBoundsException e){
					
				}
			} else {
				pinyinName += nameChar[i];
			}
		}
		return pinyinName;
	}

3.执行效果

 

 

 

你可能感兴趣的:(java)