最近的项目需要一个功能,将城市名称按首字母查询并加入索引,百度、谷歌了好久,看到的文章解决方案大概相同,就是:通过汉字对应的国际一级汉字区位码进行获取首字母,但是目前一级区位码收录的汉字并不是特别多,有很多汉字还是无法通过此方法获取,具体请查看:GBK2312编码范围,GBK编码范围
1.方式一
根据GBK2312编码范围记载
通过国标一级区位码获取首字母时,只有在16-55区的一级汉字是通过拼音排序,并且能得到首字母,不在此区域的汉字也就无法获取了。
推荐一篇文章帮助学习用此方式来获取首字母:
https://blog.csdn.net/u012532559/article/details/51312820
还有一篇文章与这个类似,找不到原文了,贴一下他的源码吧(如果原博主看到,可以联系换成原文链接,实在不好意思,多谢多谢)
代码如下:
private static final int GB_SP_DIFF = 160;
// 存放国标一级汉字不同读音的起始区位码
private static final int[] secPosValueList = {1601, 1637, 1833, 2078, 2274, 2302,
2433, 2594, 2787, 3106, 3212, 3472, 3635, 3722, 3730, 3858, 4027,
4086, 4390, 4558, 4684, 4925, 5249, 5600};
private final static String[] lc_FirstLetter = {"a", "b", "c", "d", "e",
"f", "g", "h", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
"t", "w", "x", "y", "z"};
/**
* 获取一个汉字的拼音首字母。 GB码两个字节分别减去160,转换成10进制码组合就可以得到区位码
* 例如汉字“你”的GB码是0xC4/0xE3,分别减去0xA0(160)就是0x24/0x43
* 0x24转成10进制就是36,0x43是67,那么它的区位码就是3667,在对照表中读音为‘n’
*/
private static char convert(byte[] bytes) {
char result = '-';
int secPosValue = 0;
int i;
for (i = 0; i < bytes.length; i++) {
bytes[i] -= GB_SP_DIFF;
}
secPosValue = bytes[0] * 100 + bytes[1];
for (i = 0; i < 23; i++) {
if (secPosValue >= secPosValueList[i]
&& secPosValue < secPosValueList[i + 1]) {
result = firstLetter[i];
break;
}
}
return result;
}
/**
* 调用方法
* @param str 中文串
* @return 声母串
*/
public static String getAllFirstLetter(String str) {
if (str == null || str.trim().length() == 0) {
return "";
}
String _str = "";
for (int i = 0; i < str.length(); i++) {
_str = _str + getFirstLetter(str.substring(i, i + 1));
}
return _str;
}
/**
* 每个字的首字母
*
* @param chinese 汉字
* @return 返回声母
*/
public static String getFirstLetter(String chinese) {
if (chinese == null || chinese.trim().length() == 0) {
return "";
}
chinese = conversionStr(chinese, "GB2312", "ISO8859-1");
if (chinese.length() > 1){ // 判断是不是汉字
int li_SectorCode = (int) chinese.charAt(0); // 汉字区码
int li_PositionCode = (int) chinese.charAt(1); // 汉字位码
li_SectorCode = li_SectorCode - 160;
li_PositionCode = li_PositionCode - 160;
int li_SecPosCode = li_SectorCode * 100 + li_PositionCode; // 汉字区位码
if (li_SecPosCode > 1600 && li_SecPosCode < 5590) {
for (int i = 0; i < 23; i++) {
if (li_SecPosCode >= secPosValueList[i]
&& li_SecPosCode < secPosValueList[i + 1]) {
chinese = lc_FirstLetter[i];
break;
}
}
} else {// 非汉字字符,如图形符号或ASCII码
chinese = conversionStr(chinese, "ISO8859-1", "GB2312");
chinese = chinese.substring(0, 1);
}
}
return chinese;
}
/**
* 字符串编码转换
* @param str 要转换编码的字符串
* @param charsetName 原来的编码
* @param toCharsetName 转换后的编码
* @return 经过编码转换后的字符串
*/
private static String conversionStr(String str, String charsetName, String toCharsetName) {
try {
str = new String(str.getBytes(charsetName), toCharsetName);
} catch (UnsupportedEncodingException ex) {
System.out.println("字符串编码转换异常:" + ex.getMessage());
}
return str;
}
2.方式二
GitHub上的项目:https://github.com/promeG/TinyPinyin
因为我的项目中只使用到的是字符串的首字母,我是通过截取的方式拿到的。具体实现方法可以查看原文,集成到项目中使用就行了。
多谢指教!