• Java中汉字转拼音


    需要下载pinyin4j:http://pinyin4j.sourceforge.net/

    代码
    package utils;

    import net.sourceforge.pinyin4j.*;
    import net.sourceforge.pinyin4j.format.*;
    import net.sourceforge.pinyin4j.format.exception.*;

    public class PinYin {
        
    /**
         * 将汉字转换为全拼
         * 
         * 
    @param src
         * 
    @return
         
    */
        
    public static String getPingYin(String src) {
            
    char[] t1 = null;
            t1 
    = src.toCharArray();
            String[] t2 
    = new String[t1.length];
            HanyuPinyinOutputFormat t3 
    = new HanyuPinyinOutputFormat();
            t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
            t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
            t3.setVCharType(HanyuPinyinVCharType.WITH_V);
            String t4 
    = "";
            
    int t0 = t1.length;
            
    try {
                
    for (int i = 0; i < t0; i++) {
                    
    // 判断是否为汉字字符
                    if (java.lang.Character.toString(t1[i]).matches(
                            
    "[\\u4E00-\\u9FA5]+")) {
                        t2 
    = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);
                        t4 
    += t2[0];
                    } 
    else
                        t4 
    += java.lang.Character.toString(t1[i]);
                }
                
    // System.out.println(t4);
                return t4;
            } 
    catch (BadHanyuPinyinOutputFormatCombination e1) {
                e1.printStackTrace();
            }
            
    return t4;
        }

        
    /**
         * 返回中文的首字母
         * 
         * 
    @param str
         * 
    @return
         
    */
        
    public static String getPinYinHeadChar(String str) {

            String convert 
    = "";
            
    for (int j = 0; j < str.length(); j++) {
                
    char word = str.charAt(j);
                String[] pinyinArray 
    = PinyinHelper.toHanyuPinyinStringArray(word);
                
    if (pinyinArray != null) {
                    convert 
    += pinyinArray[0].charAt(0);
                } 
    else {
                    convert 
    += word;
                }
            }
            
    return convert;
        }

        
    public static void main(String[] args) {
            String cnStr 
    = "中华人民共和国";
            System.out.println(getPingYin(cnStr));
            System.out.println(getPinYinHeadChar(cnStr));
        }
    }
  • 相关阅读:
    angularJs实现级联操作
    FastDFS简单入门小demo
    FastDFS初步认识--上传下载流程介绍
    什么是spu和sku
    centOS7 flask项目布署
    Error: Another program is already listening on a port that one of our HTTP servers is configured to use. Shut this program down first before starting supervisord.
    gunicorn+nginx配置方法
    supervisor的使用
    【linux】杀掉进程命令
    CentOS7 nginx安装与卸载
  • 原文地址:https://www.cnblogs.com/yvesliao/p/1773040.html
Copyright © 2020-2023  润新知