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

      

  • 相关阅读:
    调试相关blogs收集
    union和union all
    V$SQLAREA
    Oracle Access和filter的区别
    Oracle 复合索引设计原理——前缀性和可选性
    经济学原理---8应用:税收的代价--- 读书笔记
    经济学原理---7 消费者.生产者与市场效率--- 读书笔记
    经济学原理---6 供给.需求与政府政策--- 读书笔记
    经济学原理---5 弹性及其应用 --- 读书笔记
    CURL---常见问题
  • 原文地址:https://www.cnblogs.com/TulipsWill/p/12849032.html
Copyright © 2011-2022 走看看