zoukankan      html  css  js  c++  java
  • java汉字转拼音

    一、maven依赖包

            <dependency>
                <groupId>com.belerweb</groupId>
                <artifactId>pinyin4j</artifactId>
                <version>2.5.0</version>
            </dependency>
    

      

    二、代码

    package com.company.project.common.utils;
    
    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.exception.BadHanyuPinyinOutputFormatCombination;
    
    public class PinYinUtil {
    
        public static void main(String[] args) {
            //输出:ZHANGSAN
            System.out.println(toPinyin("张三").toUpperCase());
    
            //输出:zs
            System.out.println(toFirstChar("张三"));
        }
    
        /**
         * 汉字转换为拼音首字母
         * @param chinese 汉字
         * @return
         */
        public static String toFirstChar(String chinese){
            String convert = "";
            for (int j = 0; j <  chinese.length(); j++) {
                char word = chinese.charAt(j);
                String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
                if (pinyinArray != null) {
                    convert += pinyinArray[0].charAt(0);
                } else {
                    convert += word;
                }
            }
            return convert;
        }
    
        /**
         * 汉字转全拼
         * @param chinese 汉字
         * @return
         */
        public static String toPinyin(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 += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0];
                    } catch (BadHanyuPinyinOutputFormatCombination e) {
                        e.printStackTrace();
                    }
                } else {
                    pinyinStr += newChar[i];
                }
            }
            return pinyinStr;
        }
    }
    

      

  • 相关阅读:
    [luoguU48834][count]
    [ZROJ110][假如战争今天爆发]
    [luogu4860][Roy&October之取石子II]
    [luogu4018][Roy&October之取石子]
    [luoguU48574][藏妹子之处]
    [20181025晚][模拟赛]
    [20181025上午][模拟赛]
    ElasticSearch业务逻辑案例
    ElasticSearch安装及使用
    面试必问:ACID/CAP
  • 原文地址:https://www.cnblogs.com/TulipsWill/p/12849032.html
Copyright © 2011-2022 走看看