首页 > 技术文章 > JAVA-汉字转换成汉语拼音(pinyin4j-2.5.0-sources.jar)

xiangpeng 2018-04-23 09:31 原文

在项目中,经常会使用汉语拼音,特别是把汉字转换成汉语拼音。下面给出一种常用的工具。

在使用该程序必须添加 pinyin4j-2.5.0-sources.jar包。

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 ToPinyinString {
    // 将汉字转换为全拼
    public static String getPingYin(String src) {
        char[] t1 = null;
        t1 = src.toCharArray();
        String[] t2 = new String[t1.length];
        HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();

        t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);     //返回小写
        t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);  //返回无声调
        t3.setVCharType(HanyuPinyinVCharType.WITH_V);      //以V表示该字符
        String t4 = "";
        int t0 = t1.length;
        try {
            for (int i = 0; i < t0; i++) {
                // 判断是否为汉字字符
                if (java.lang.Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")){ //正则表达式,至少匹配一个汉字
                    t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);
                    t4 += t2[0];
                } else
                    t4 += java.lang.Character.toString(t1[i]);
            }
            return t4;
        } catch (BadHanyuPinyinOutputFormatCombination e1) {
            e1.printStackTrace();
        }
        return t4;
    }

    // 返回中文的首字母
    public static String getPinYinHeadChar(String str) {
        String convert = "";
        for (int j = 0; j < str.length(); j++) {
            char word = str.charAt(j);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert += pinyinArray[0].charAt(0);
            } else {
                convert += word;
            }
        }
        return convert;
    }

    // 将字符串转移为ASCII码
    public static String getCnASCII(String cnStr) {
        StringBuffer strBuf = new StringBuffer();
        byte[] bGBK = cnStr.getBytes();
        for (int i = 0; i < bGBK.length; i++) {
            strBuf.append(Integer.toHexString(bGBK[i] & 0xff));
        }
        return strBuf.toString();
    }
    public static void main(String[] args) {

    System.out.println("汉字转汉语拼音:"+getPingYin("美丽的zhongguo,我的故乡"));
    System.out.println("汉字首字母:"+getPinYinHeadChar("美丽的zhongguo,我的故乡"));
    System.out.println("汉字转 ASCII值:"+getCnASCII("美丽的zhongguo,我的故乡"));

    }
}

如上代码所示,Run As打印的结果如下所示:

 当然可以根据该代码,扩展一系列的功能。如转换成大写字母等。

推荐阅读