欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

汉字转全拼和拼音

程序员文章站 2022-07-15 14:59:30
...
        <dependency>
            <groupId>com.belerweb</groupId>
            <artifactId>pinyin4j</artifactId>
            <version>2.5.0</version>
        </dependency>

以下是工具类,粘贴即可使用(转换后均是大写)

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 Conversion {
    /*
       汉字得到全拼
     */
    public static String getPinYin( String str ){
        char[] w1 = null;
        w1 = str.toCharArray();
        String[] w2 = new String[w1.length];
        HanyuPinyinOutputFormat w3 = new HanyuPinyinOutputFormat();
        w3.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        w3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        w3.setVCharType(HanyuPinyinVCharType.WITH_V);
        String w4 = "";
        int w0 = w1.length;
        try{
            for ( int i = 0; i < w0; i++ ) {
                //判断是否为汉字字符
                if ( java.lang.Character.toString(w1[i]).matches("[\\u4E00-\\u9FA5]+") ){
                    w2 = PinyinHelper.toHanyuPinyinStringArray(w1[i],w3);
                    w4 += w2[0];
                }else {
                    w4 += java.lang.Character.toString(w1[i]);
                }
            }
            return w4;
        }catch ( BadHanyuPinyinOutputFormatCombination e ){
            e.printStackTrace();
        }
        return w4;
    }
    /*
       汉字转简拼
     */
    public static String getPinYinHeadChar( String str ){
        String conver = "";
        if ( str == null || str.length() == 0 ){
            return conver;
        }
        for ( int j = 0; j < str.length(); j++ ){
            char word = str.charAt(j);
            //提取汉字的首字母
            String[] strings = PinyinHelper.toHanyuPinyinStringArray(word);
            if ( strings != null ){
                conver += strings[0].charAt(0);
            }else {
                conver += word;
            }
        }
        return conver.toUpperCase();
    }
}