200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > java获取汉字的拼音首字母_Java获取汉字拼音首字母

java获取汉字的拼音首字母_Java获取汉字拼音首字母

时间:2020-11-22 10:04:42

相关推荐

java获取汉字的拼音首字母_Java获取汉字拼音首字母

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

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

import java.io.UnsupportedEncodingException;

/**

* Created by IntelliJ IDEA.

* User: Hex

* Date: -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("你好"));

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。