汉字转拼音/全拼/首字母

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

项目中需要通过组织名称获取对应的简拼,便写了一个工具类,其实也是简单的调用


一、Pinyin4j 简介

Pinyin4j 是一个流行的 Java 库,支持汉字和最流行的拼音系统之间的转换。拼音的输出格式可以自定义。 我们使用只需要调用即可。
官网地址:http://pinyin4j.sourceforge.net/

二、使用步骤

1.引入依赖

代码如下(示例):

	   <!-- 中文转拼音 -->
       <dependency>
           <groupId>com.belerweb</groupId>
           <artifactId>pinyin4j</artifactId>
           <version>2.5.0</version>
       </dependency>

2.具体实现

引入依赖后,可以直接复制下面代码,作为工具类,直接调用即可,这种没法分辨多音字,有需要可以去官网查看最新的接口

代码如下(示例):

public class SpellingUtil {

    /**
     * 得到 全拼
     *
     * @param word
     * @return
     */
    public static String getPingYin(String word) {
        if (word == null || "".equals(word)) {
            return "";
        }
        char[] codes = word.toCharArray();

        HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
        outputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        outputFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
        String result = "";
        try {
            for (int i = 0; i < codes.length; i++) {
                // 判断是否为汉字字符
                if (java.lang.Character.toString(codes[i]).matches("[\\u4E00-\\u9FA5]+")) {
                    String[] allPinyin = PinyinHelper.toHanyuPinyinStringArray(codes[i], outputFormat);
                    // 多音字默认取第一个
                    result += allPinyin[0];
                } else {
                    result += java.lang.Character.toString(codes[i]);
                }
            }
            return result;
        } catch (BadHanyuPinyinOutputFormatCombination e1) {
            e1.printStackTrace();
        }
        return result;
    }

    /**
     * 得到中文首字母
     *
     * @param word
     * @return
     */
    public static String getPinYinHeadChar(String word) {
        if (word == null || "".equals(word)) {
            return "";
        }
        String result = "";
        for (int i = 0; i < word.length(); i++) {
            char code = word.charAt(i);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(code);
            if (pinyinArray != null) {
                result += pinyinArray[0].charAt(0);
            } else {
                result += code;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        String cnStr4 = "省";
        System.out.println("全拼: " + getPingYin(cnStr4));
        System.out.println("简拼: " + getPinYinHeadChar(cnStr4));


    }

}

总结

这样子就轻松完成啦,有用点个赞吧!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值