package com.gomusic.datatype;
public class CnToSpell
{
//字母Z使用了两个标签,这里有27个值
//i, u, v都不做声母, 跟随前面的字母
//存在问题,需要改进
private char[] chartable =
{
'啊', '芭', '擦', '搭', '蛾', '发', '噶', '哈', '哈',
'击', '喀', '垃', '妈', '拿', '哦', '啪', '期', '然',
'撒', '塌', '塌', '塌', '挖', '昔', '压', '匝', '座'
};
private char[] alphatable =
{
'A', 'B', 'B', '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, char two)
{
if (ch >= 'a' && ch <= 'z')
//return (char) (ch - 'a' + 'A');
return (char)(ch + 'A' - 'a');
if (ch >= 'A' && ch <= 'Z')
{
if('Z' == two)
{
return '#';
}
return ch;
}
if (ch >= '0' && ch <= '9')
return ch;
int gb = gbValue(ch);
if (gb < table[0])
return '#';
int i;
for (i = 0; i < 26; ++i)
{
if (match(i, gb))
break;
}
if (i >= 26)
return '#';
else
return alphatable[i];
}
//根据一个包含汉字的字符串返回一个汉字拼音首字母的字符串
public String getFirstCharacter(String SourceStr)
{
String Result = "";
//int StrLength = SourceStr.length();
//int i;
try
{
/*for (i = 0; i < StrLength; i++)
{
Result += charAlpha(SourceStr.charAt(i));
}*/
Result += charAlpha(SourceStr.charAt(0), SourceStr.charAt(1));
} 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];//如果是则为Z
else
return gb < table[j];//如果是则应该是i,如果不是那就返回false继续循环
}
//取出汉字的编码
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;
}
}
}
获取汉字首字母
最新推荐文章于 2021-02-17 03:25:02 发布