Blog / 阅读

java提取每个汉字的首字母

by admin on 2014-03-21 13:12:50 in ,



很多时候为了分类或者排序我们需要取得汉字的首字母,这里一个例子很好的完成了这个要求。

import net.sourceforge.pinyin4j.PinyinHelper;  

  
public class PinyinAPI {  
  
    /** 
     * 提取每个汉字的首字母(大写) 
     *  
     * @param str 
     * @return 
     */  
    public static String getPinYinHeadChar(String str) {  
        if (isNull(str)) {  
            return "";  
        }  
        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;  
            }  
        }  
  
        convert = string2AllTrim(convert);  
        return convert.toUpperCase();  
    }  
  
    /* 
     * 判断字符串是否为空 
     */  
  
    public static boolean isNull(Object strData) {  
        if (strData == null || String.valueOf(strData).trim().equals("")) {  
            return true;  
        }  
        return false;  
    }  
  
    /** 
     * 去掉字符串包含的所有空格 
     *  
     * @param value 
     * @return 
     */  
    public static String string2AllTrim(String value) {  
        if (isNull(value)) {  
            return "";  
        }  
        return value.trim().replace(" ", "");  
    }  
  
    public static void main(String[] args) {  
        String ss = PinyinAPI.getPinYinHeadChar("中国");  
        System.out.print(ss);//ZG  
    }  

}  


需要的jar包下载地址(免积分):http://download.csdn.net/detail/zl544434558/7076087


写评论

相关文章

上一篇:.net MVC实现当前页多个数据修改,按钮点击分类别显示

下一篇:DES加密算法详解- -

评论

写评论

* 必填.

分享

栏目

赞助商


热门文章

Tag 云