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

      

  • 相关阅读:
    调用外部 DLL 中的函数(显示调用)
    模式窗体与非模式窗体
    使用PChar和string类型时的内存分配技术
    保密卡程序的编写
    Dll 使用 PChar 参数的小例子
    delphi动态创建组件的颜色
    Dll 模式窗口与非模式窗口
    调用外部 DLL 中的函数(隐式调用)
    内核读写只读内存方法总结[Delphi描述][转帖]
    delphi资源文件制作及使用详解
  • 原文地址:https://www.cnblogs.com/TulipsWill/p/12849032.html
Copyright © 2011-2022 走看看