【Java将汉字转化为拼音,可控制是否首字母】

注意:需要引入一个jar包:pinyin4j-1.1.0.jar

package testmain;

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;

public class Test {

    /** (一个)中文 正则表达式 */
    private static final String CHINESE_REGEX = "[\u4e00-\u9fa5]";

    public static void main(String[] args) {
        String aa = convertChineseToPinyin("你好我是谁你知道吗11mm", true, HanyuPinyinCaseType.LOWERCASE);
        System.out.println(aa);
    }

    /**
     * 将指定字符串中的中文转为汉语拼音,其余非中文的部分不变 注:拼音小写
     *
     * @param originChinese
     *            要转成拼音的中文
     * @param abbreviation
     *            是否简写 true, 【张三】转换为【zs】 false, 【张三】转换为【zhangsan】
     * @param caseType
     *            控制拼音大小写
     *
     * @return 拼音
     * @throws BadHanyuPinyinOutputFormatCombination
     *             HanyuPinyinOutputFormat格式有误
     */
    public static String convertChineseToPinyin(String originChinese, boolean abbreviation,
            HanyuPinyinCaseType caseType) {
        // 将字符串 转换为 字符数组
        char[] chineseCharArray = originChinese.trim().toCharArray();
        // 设置转换格式
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        // 输出拼音全部小写(默认即为小写)
        defaultFormat.setCaseType(caseType);
        // 不带声调
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        /*
         * 含ü的字有 【女】【吕】【略】【虐】等
         *
         * WITH_V 设置 【ü】 转换为 【v】 , 如:【女】 转换后为 【nv】 WITH_U_AND_COLON 设置 【ü】 转换为
         * 【u:】, 如:【女】 转换后为 【nu:】 WITH_U_UNICODE 设置 【ü】 转换为 【ü】,即:原输出, 如:【女】
         * 转换后为 【nü】
         */
        defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
        StringBuilder hanYuPinYinResult = new StringBuilder(6);
        boolean isChinese;
        String tempStr;
        for (char cStr : chineseCharArray) {
            isChinese = String.valueOf(cStr).matches(CHINESE_REGEX);
            // 如果字符是中文,则将中文转为汉语拼音
            if (isChinese) {
                tempStr = PinyinHelper.toHanyuPinyinStringArray(cStr, defaultFormat)[0];
                tempStr = abbreviation ? tempStr.substring(0, 1) : tempStr;
                hanYuPinYinResult.append(tempStr);
            } else {
                // 如果字符不是中文,则不转换
                hanYuPinYinResult.append(cStr);
            }
        }
        return hanYuPinYinResult.toString();
    }

}

 

posted @ 2021-12-31 17:17  pipi-changing  阅读(45)  评论(0编辑  收藏  举报