汉字转拼音首字母或则全拼工具类

纵然是瞬间 提交于 2020-03-12 02:49:15

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;

/**
 * @ClassName:PinYinUtil
 * @Description:
 * @date 2019-08-07 18:37
 */
public class PinYinUtil { /**
 /**
 * 汉字转换为大写拼音(第一个字母)
 * 我就是我->WJSW
 */
public static String toUpFirstPinYin(String hanZhi) {
    String pinYin = "";
    char[] ch = hanZhi.toCharArray();
    for (char item : ch) {
        HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
        outputFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        String[] stringArray = new String[0];
        try {
            stringArray = PinyinHelper.toHanyuPinyinStringArray(item, outputFormat);
        } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
            badHanyuPinyinOutputFormatCombination.printStackTrace();
        }

        if (stringArray.length == 0) {
            //处理字符不是汉字的情况
            pinYin += item;
        } else {
            pinYin += stringArray[0].toCharArray()[0];
        }
    }
    return pinYin;


}

    /**
     * 汉字转换为拼音
     * 我就是我->wojiushiwo
     */
    public static String toPinYin(String hanZhi) throws BadHanyuPinyinOutputFormatCombination {
        String pinYin = "";
        char[] ch = hanZhi.toCharArray();
        for (char item : ch) {
            HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
            outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
            String[] stringArray = PinyinHelper.toHanyuPinyinStringArray(item, outputFormat);

            if (stringArray.length == 0) {
                //处理字符不是汉字的情况
                pinYin += item;
            } else {
                pinYin += stringArray[0];
            }
        }
        return pinYin;
    }

    // 解释
    public static void test() {
        HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
        // UPPERCASE:大写  (ZHONG)
        // LOWERCASE:小写  (zhong)
        outputFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);

        // WITHOUT_TONE:无音标  (zhong)
        // WITH_TONE_NUMBER:1-4数字表示英标  (zhong4)
        // WITH_TONE_MARK:直接用音标符(必须WITH_U_UNICODE否则异常)  (zhòng)
        outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        // WITH_V:用v表示ü  (nv)
        // WITH_U_AND_COLON:用"u:"表示ü  (nu:)
        // WITH_U_UNICODE:直接用ü (nü)
        outputFormat.setVCharType(HanyuPinyinVCharType.WITH_U_AND_COLON);
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!