since.2006  

根据网上C#版和JAVA版改的。代码很短,但有些复杂的汉字取不了拼音,如“鑫”等。适用一般不是很复杂的情况。

如要更完整的版本,可以使用这个开源的pinyin4j组件。

package com.since2006.commons;

import java.io.UnsupportedEncodingException;

/**
 * Created by IntelliJ IDEA.
 * User: Hex
 * Date: 2009-1-15
 * Time: 12:47:24
 */
public class GB2Alpha {

    private static final int[] AREA_CODE = new int[]{
            45217, 45253, 45761, 46318, 46826, 47010, 47297, 47614, 48119, 48119, 49062,
            49324, 49896, 50371, 50614, 50622, 50906, 51387, 51446, 52218, 52698, 52698,
            52698, 52980, 53689, 54481
    };

    public static String getFirstAlpha(String text) {

        if (text == null || "".equals(text)) {
            return "";
        }

        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < text.length(); i++) {

            sb.append(getAlpha(text.substring(i, i + 1)));

        }

        return sb.toString();
    }

    private static String getAlpha(String character) {

        byte[] bytes;
        try {
            bytes = character.getBytes("GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return character;
        }

        if (bytes.length < 2) {
            return character;
        }

        int area = (short) bytes[0];
        int pos = (short) bytes[1];
        int code = (area << 8 & 0xff00) + (pos & 0xff);

        for (int i = 0; i < 26; i++) {
            int max = 55290;
            if (i != 25) {
                max = AREA_CODE[i + 1];
            }
            if (AREA_CODE[i] <= code && code < max) {
                return new String(new byte[]{(byte) (65 + i)});
            }
        }

        return character;
    }

    public static void main(String[] args) {

        System.out.println(getFirstAlpha("你好"));
    }
}

Posted by hee at 10:04 AM | Permalink | 评论(1) | Java

2283 天 12 小时前
沙发 云帝xiao堕 说:

非常感谢~ 很好用

请输入名称
请输入邮件地址

 

    请输入邮件地址