取出汉字的拼音首字母

来源:互联网 发布:react.js vue.js 编辑:程序博客网 时间:2024/04/27 03:46
首先下载pinyin4j.jar包,这也是一个开源的东东,在此基础上改了一下,取汉字拼音的首字母。
 package com.general;
/*
import java.io.IOException;
 
import java.io.InputStreamReader;
 
import java.io.BufferedReader;
*/
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.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
 
/**
 * @author Linuxok
 *  
 * 此程序取得汉字的拼音第一个字母
 */
public class GB2Py {
 
    /**
     * 此程序取得汉字的拼音第一个字母
     *  
     * @param str:汉字字符
     * @return 汉字拼音的第一个字母的组合
     */
    public static String getFirstLetter(String str) {
 
        HanyuPinyinOutputFormat hp = new HanyuPinyinOutputFormat();
        hp.setCaseType(HanyuPinyinCaseType.LOWERCASE); // 设定输出是大写还是小写英文字LOWERCASE,UPPERCASE
        hp.setToneType(HanyuPinyinToneType.WITHOUT_TONE); // 是否要标出声调
        hp.setVCharType(HanyuPinyinVCharType.WITH_V); // 输出是要用何种编码
        String[] t0 = new String[10];
        StringBuffer buffer = new StringBuffer("");
        char ch;
        char[] temp;
        try {
            for (int i = 0; i < str.length(); i++) { // 依次处理str中每个字符
                ch = str.charAt(i);
                temp = new char[] { ch };
                byte[] uniCode = new String(temp).getBytes();
                if (uniCode[0] < 128 && uniCode[0] > 0){
                    t0[0] = String.valueOf(temp[0]);
                }else {
                    t0 = PinyinHelper.toHanyuPinyinStringArray(ch, hp);
                }
                if (t0 != null)
                    buffer.append(t0[0].substring(0, 1));
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }
/*
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String inStr = "";
        while (true) {
            System.out.println("此程序测试取汉字第一个拼音字母,请输入汉字字符:");
            inStr = in.readLine();
            if (inStr.equals("end")) {
                break;
            }
            System.out.println(GB2Py.getFirstLetter(inStr));
        }
    }
*/
}
原创粉丝点击