汉字生成拼音码


            com.belerweb
            pinyin4j
            2.5.0
        

依赖

项目地址:https://github.com/belerweb/pinyin4j

方法:

package com.zengziqiang.utils;

import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * @author [email protected]
 * @Version: 1.0
 * @desc //todo
 */
public class PinyinHelp {

    public static String too(String chinese) {
        String pinyinStr = "";
        char[] newChar = chinese.toCharArray();  //转为单个字符
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < newChar.length; i++) {
            if (newChar[i] > 128) {
                try {
                    pinyinStr += net.sourceforge.pinyin4j.PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0].charAt(0);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pinyinStr += newChar[i];
            }
        }
        return pinyinStr;

    }

    public static void main(String[] args) {
        System.out.println(too("汉字转换为拼音").toUpperCase()); //转为首字母大写---->HZZHWPY
        System.out.println(too("齉字转换为拼音").toUpperCase()); //转为首字母大写---->HZZHWPY

    }

}

输出:

HZZHWPY
NZZHWPY

 

你可能感兴趣的:(Java)