汉字转全拼和拼音

        <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();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值