📄 gb2alphat.java
字号:
/**
* 取汉字首字母
*
* @author shixin
* 注:有些汉字并未按照 字母顺序出现在GB2312简体中文编码表中 而是出现在D8A0以及其后面的区域 对这些汉字都只会转化为0
*/
public class GB2Alphat {
// 因为要设置结束位所以字母Z使用了两个标签,这里有27个值
// i, u, v都不做声母, 跟随前面的字母
private static char[] chartable = { '啊', '芭', '擦', '搭', '蛾', '发', '噶', '哈',
'哈', '击', '喀', '垃', '妈', '拿', '哦', '啪', '期', '然', '撒', '塌', '塌',
'塌', '挖', '昔', '压', '匝', '座' };
// 字母表
private static char[] alphattable = { 'A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z' };
// 汉字表对应的字符编码表
private int[] table = new int[27];
public GB2Alphat() {
for (int i = 0; i < 27; i++)
table[i] = getGb(chartable[i]);
}
// 获取输入汉字的字符编码
private static int getGb(char ch) {
String str = new String();
str += ch;
try {
byte[] bytes = str.getBytes("GB2312");
// 确保每一个汉字的编码是唯一的;因为byte类型表示的范围小,直接使用byte则汉字编码会发生重复
// 把bytes[0]作为高位,bytes[1]作为低位相加
return (bytes[0] << 8 & 0xff00) + (bytes[1] & 0xff);
} catch (Exception e) {
return 0;
}
}
// 把字符转化成字母
public char gb2A(char ch) {
if (ch >= 'a' && ch <= 'z')
return (char) (ch - 'a' + 'A');
if (ch >= 'A' && ch <= 'Z')
return ch;
int gb = getGb(ch);
if (gb < table[0])
return '0';
int i;
for (i = 0; i < 26; i++) {
if (match(i, gb))
break;
}
if (i >= 26)
return '0';
else
return alphattable[i];
}
// 对给定字母的编码与table进行匹配,匹配方法:i为table第i个元素,如果gb>i并且gb<i+1则表明该gb是以第I个元素开头的,就返回true.
public boolean match(int i, int gb) {
int j = i + 1;
if (j == 26)
return gb <= table[j];
else
return gb < table[j];
}
// 对字符串进行转换
public String str2StrA(String str) {
String result = "";
for (int i = 0; i < str.length(); i++) {
result += gb2A(str.charAt(i));
}
return result;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -