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

      

  • 相关阅读:
    webstorm之js,css文件压缩
    Dojo的UI框架bootstrap for dojo和Dojo-Bootstrap简介
    android 之 java环境部署
    利用requestjs优化响应式移动端js加载
    前端自动化部署之gulp
    ubuntu配置LAMP
    html5的116个标签
    前端环境安装(node.js+npm+grunt+bower)
    git在webstorm中的使用
    JDK下载安装与环境变量path配置
  • 原文地址:https://www.cnblogs.com/TulipsWill/p/12849032.html
Copyright © 2020-2023  润新知