首页 > 编程 > Java > 正文

java获取中文拼音首字母工具类定义与用法实例

2019-11-26 08:26:01
字体:
来源:转载
供稿:网友

本文实例讲述了java获取中文拼音首字母工具类定义与用法。分享给大家供大家参考,具体如下:

package com.sw.documentary.common.utils;public class GB2Alpha {  //字母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]);    }  }  public GB2Alpha() {  }  //主函数,输入字符,得到他的声母,  //英文字母返回对应的大写字母  //其他非简体汉字返回 '0'  public char Char2Alpha(char ch) {    if (ch >= 'a' && ch <= 'z')      return (char) (ch - 'a' + 'A');    if (ch >= 'A' && ch <= 'Z')      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 String2Alpha(String SourceStr){    String Result = "";    int StrLength = SourceStr.length();    int i;    try {      for (i = 0; i < StrLength; i++) {        Result += Char2Alpha(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) {    GB2Alpha obj1 = new GB2Alpha();    System.out.println(obj1.String2Alpha("武林网"));    System.out.println(obj1.String2Alpha("欢迎你"));    return;  }}

运行结果:

JBZJ
HYN

PS:这里再为大家提供几款本站拼音与字母相关工具供大家参考:

在线中英文根据首字母排序工具:
http://tools.VeVB.COm/aideddesign/zh_paixu

在线汉字转换成拼音工具:
http://tools.VeVB.COm/transcoding/pinyin

在线中文汉字转拼音工具:
http://tools.VeVB.COm/transcoding/hanzi2pinyin

在线中文汉字拼音对照转换工具:
http://tools.VeVB.COm/transcoding/zh_pinyin

在线字母大小写转换工具:
http://tools.VeVB.COm/transcoding/upper

更多关于java相关内容感兴趣的读者可查看本站专题:《Java数组操作技巧总结》、《Java字符与字符串操作技巧总结》、《Java数学运算技巧总结》、《Java数据结构与算法教程》及《Java操作DOM节点技巧总结

希望本文所述对大家java程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表