ITPub博客

首页 > 应用开发 > Java > java获取汉字的首字母

java获取汉字的首字母

原创 Java 作者:livedba 时间:2012-04-09 16:16:19 0 删除 编辑
java获取汉字的首字母工具类[@more@]

package net.uni.util;

/**
* 处理内容:获得输入汉字的首字母
* @version: 1.0
* @see:net.uni.util.CnToSpell.java
* @date:2012-4-9
* @author:孙伟
*/
public class CnToSpell {

//字母Z使用了两个标签,这里有27个值
//i, u, v都不做声母, 跟随前面的字母
private char[] chartable =
{
'啊', '芭', '擦', '搭', '蛾', '发', '噶', '哈', '哈',
'击', '喀', '垃', '妈', '拿', '哦', '啪', '期', '然',
'撒', '塌', '塌', '塌', '挖', '昔', '压', '匝', '座'
};

private char[] alphatable =
{
'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];
//初始化
{
for (int i = 0; i < 27; ++i) {
table[i] = gbValue(chartable[i]);
}
}


//主函数,输入字符,得到他的声母,
//英文字母返回对应的小写字母
//其他非简体汉字返回 '0'
public char charAlpha(char ch){
if (ch >= 'a' && ch <= 'z')
//return (char) (ch - 'a' + 'A');
return ch;
if (ch >= 'A' && ch <= 'Z')
return (char) (ch - 'A' + 'a');
if (ch >= '0' && ch <= '9')
return ch;
int gb = gbValue(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 alphatable[i];
}

//根据一个包含汉字的字符串返回一个汉字拼音首字母的字符串
public String getBeginCharacter(String SourceStr){

String Result = "";
int StrLength = SourceStr.length();
int i;
try {
for (i = 0; i < StrLength; i++) {
Result += charAlpha(SourceStr.charAt(i));
}
} catch (Exception e){
Result = "";
}
return Result;
}

private boolean match(int i, int gb){

if (gb < table[i])
return false;
int j = i + 1;

//字母Z使用了两个标签
while (j < 26 && (table[j] == table[i])) ++j;
if (j == 26)
return gb <= table[j];
else
return gb < table[j];
}

//取出汉字的编码
private int gbValue(char ch){

String str = new String();
str += ch;
try{
byte[] bytes = str.getBytes("GB2312");
if (bytes.length < 2)
return 0;
return (bytes[0] << 8 & 0xff00) + (bytes[1] &
0xff);
} catch (Exception e){
return 0;
}
}

public static void main(String[] args){
CnToSpell obj1 = new CnToSpell();
System.out.println(obj1.getBeginCharacter("测试数据8ADGaadf"));
return;
}
}

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/25261409/viewspace-1057862/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2011-01-21

  • 博文量
    115
  • 访问量
    483874