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("鑫淼焱犇驫樸"));
    }
}


運行結果:

po.biao.ben.yan.miao.xin123

參考鏈接:https://www.cnblogs.com/zh-1721342390/p/8276922.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章