java实现中文汉字转拼音 Pinyin4j的基本用法

一、前言

工作中有时候会遇到汉字拼音转换的需求,例如:用户首字母搜索某个内容的时候,wzry 可搜索 王者荣耀相关的。
这里推荐使用Pinyin4j,它是sourceforge.net上的一个开源项目,提供了许多强大的处理汉语拼音相关问题的方法。详情可参考:http://pinyin4j.sourceforge.net/

二、使用Pinyin4j

1、maven项目添加依赖包
<!-- 汉语 拼音 转换的包-->
<dependency>
    <groupId>com.belerweb</groupId>
    <artifactId>pinyin4j</artifactId>
    <version>2.5.0</version>
</dependency>
2、汉字转拼音工具类(具体看注释)
package com.sam.util;

import net.sourceforge.pinyin4j.PinyinHelper;
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;

/**
 * 中文汉字转拼音工具类
 *
 * @author sam
 * @since 2017/5/10
 */
public class PinyinUtil {

    public static void main(String[] args) throws BadHanyuPinyinOutputFormatCombination {

        String str = PinyinUtil.getPinYinHeadChar("小超人");
        System.out.println(str);

//        String[] strs = PinyinUtil.getPinYin('空');
//        for (String str : strs) {
//            System.out.println(str);
//        }

    }

    /**
     * 传入中文获取首字母 (小写)
     * 如:小超人 -> xcr
     *
     * @param str 需要转化的中文字符串
     * @return
     */
    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;
    }


    /**
     * 获取中文字的拼音(多音字,拼音后的数字代表第几声)
     * 如:空 -> kong1 kong4
     *
     * @param word
     * @return
     */
    public static String[] getPinYin(char word) {
        return PinyinHelper.toHanyuPinyinStringArray(word);
    }

    /**
     * 获取中文字的拼音(多音字,拼音上的符号代表第几声)
     * 如:空 -> kōng kòng
     *
     * @param word
     * @return
     */
    public static String[] getPinYinWithToneMark(char word) throws BadHanyuPinyinOutputFormatCombination {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setToneType(HanyuPinyinToneType.WITH_TONE_MARK);
        format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
        return PinyinHelper.toHanyuPinyinStringArray(word, format);
    }


}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值