/**
* 获得单个汉字的ascii.
* @param cn char
* 汉字字符
* @return int
* 错误返回 0,否则返回ascii
*/
public static int getcnascii(char cn)
{
byte[] bytes = (string.valueof(cn)).getbytes();
if(bytes == null || bytes.length > 2 || bytes.length <= 0){ //错误
return 0;
}
if(bytes.length == 1){ //英文字符
return bytes[0];
}
if(bytes.length == 2){ //中文字符
int hightbyte = 256 bytes[0];
int lowbyte = 256 bytes[1];
int ascii = (256 * hightbyte lowbyte) - 256 * 256;
//system.out.println("ascii=" ascii);
return ascii;
}
return 0; //错误
}
/**
* 根据ascii码到spellmap中查找对应的拼音
* @param ascii int
* 字符对应的ascii
* @return string
* 拼音,首先判断ascii是否>0&<160,如果是返回对应的字符,
*
否则到spellmap中查找,如果没有找到拼音,则返回null,如果找到则返回拼音.
*/
public static string getspellbyascii(int ascii)
{
if(ascii > 0 && ascii < 160){ //单字符
return string.valueof((char)ascii);
}
if(ascii < -20319 || ascii > -10247){ //不知道的字符
return null;
}
set keyset = spellmap.keyset();
iterator it = keyset.iterator();
string spell0 = null;;
string spell = null;
int asciirang0 = -20319;
int asciirang;
while(it.hasnext()){
spell = (string)it.next();
object valobj = spellmap.get(spell);
if(valobj instanceof integer){
asciirang = ((integer)valobj).intvalue();
if(ascii >= asciirang0 && ascii < asciirang){ //区间找到
return(spell0 == null) ? spell : spell0;
}
else{
spell0 = spell;
asciirang0 = asciirang;
}
}
}
return null;
}
/**
* 返回字符串的全拼,是汉字转化为全拼,其它字符不进行转换
* @param cnstr string
* 字符串
* @return string
* 转换成全拼后的字符串
*/
public static string getfullspell(string cnstr)
{
if(null == cnstr || "".equals(cnstr.trim())){
return cnstr;
}
char[] chars = cnstr.tochararray();
stringbuffer retubuf = new stringbuffer();
for(int i = 0,len = chars.length;i < len;i ){
int ascii = getcnascii(chars[i]);
if(ascii == 0){ //取ascii时出错
retubuf.append(chars[i]);
}
else{
string spell = getspellbyascii(ascii);
if(spell == null){
retubuf.append(chars[i]);
}
else{
retubuf.append(spell);
} // end of if spell == null
} // end of if ascii <= -20400
} // end of for
return retubuf.tostring();
}
public static string getfirstspell(string cnstr)
{
return null;
}
public static void main(string[] args)
{
string str = null;
str = "谢海101普降喜雨";
system.out.println("spell=" cntospell.getfullspell(str));
str = "张牙舞爪》。,";
system.out.println("spell=" cntospell.getfullspell(str));
str = "李鹏,可耻下场。";
system.out.println("spell=" cntospell.getfullspell(str));
str = "猪油,猪八戒。";
system.out.println("spell=" cntospell.getfullspell(str));
}
}