Java 汉字转拼音(倒叙显示,过滤字符,字母,有数字添加到末尾)

汉字转拼音(倒叙显示,过滤字符,字母,有数字添加到末尾)

第三方架包下载地址:https://sourceforge.net/projects/pinyin4j/files/


package a;
import java.util.LinkedList;
import java.util.regex.Pattern;

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 HanyuPinyinHelper {

    /** 
     * 将文字转为汉语拼音
     * @param chineselanguage 要转成拼音的中文
     */
    public String toHanyuPinyin(String ChineseLanguage){
        char[] cl_chars = ChineseLanguage.trim().toCharArray();
        StringBuffer hanyupinyin = new StringBuffer(); // 拼音
        StringBuffer number = new StringBuffer(); // 数字
        LinkedList<String> linkedList = new LinkedList<>();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);// 输出拼音全部小写
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 不带声调
        defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V) ;
        try {
            for (int i=0; i<cl_chars.length; i++){
                if (String.valueOf(cl_chars[i]).matches("[\u4e00-\u9fa5]+")){// 如果字符是中文,则将中文转为汉语拼音
                  //  hanyupinyin += PinyinHelper.toHanyuPinyinStringArray(cl_chars[i], defaultFormat)[0];
                	linkedList.add(PinyinHelper.toHanyuPinyinStringArray(cl_chars[i], defaultFormat)[0]);
                } else {// 如果字符不是中文,则不转换
                    //hanyupinyin += cl_chars[i];
//                	linkedList.add();
                	if (Pattern.matches("\\d+", String.valueOf(cl_chars[i]))) {
                		number.append(String.valueOf(cl_chars[i]));
                	}
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            System.out.println("字符不能转成汉语拼音");
        }
        for (int i = linkedList.size() -1 ; i >= 0; i--) {
        	hanyupinyin.append(linkedList.get(i)+".");
		}
        String fullStr = hanyupinyin.toString().substring(0 , hanyupinyin.length() -1);
        return fullStr + number;
    }
    
    public static void main(String[] args) {
        HanyuPinyinHelper hanyuPinyinHelper = new HanyuPinyinHelper() ;
        System.out.print(hanyuPinyinHelper.toHanyuPinyin("鑫淼焱犇骉朴"));
    }
}


参考链接:https://www.cnblogs.com/zh-1721342390/p/8276922.html

猜你喜欢

转载自blog.csdn.net/immortalityWang/article/details/80055733