当前位置: 移动技术网 > IT编程>开发语言>Java > Java获取中文拼音、中文首字母缩写和中文首字母的示例

Java获取中文拼音、中文首字母缩写和中文首字母的示例

2019年07月22日  | 移动技术网IT编程  | 我要评论

我们有时候会遇到这样的情况,需要获取某些中文的拼音、中文首字母缩写和中文首字母,下面我将为大家介绍一下如何获取中文拼音的缩写。

1、项目建立和配置

首先,我们建立一个java项目,新建libs文件夹并引入一个734a7099-4830-39f2-a136-0e850ccdcc7a.jar文件,这个步骤相信就不用详细写了,跳过。

2、获取中文拼音(如:广东省 -->guangdongsheng)

</pre><pre name="code" class="java"><span style="white-space:pre">  </span>/** 
   * 得到中文全拼 
   * @param src 需要转化的中文字符串 
   * @return 
   */ 
  public static string getpingyin(string src) 
  { 
    char[] t1 = null; 
    t1 = src.tochararray(); 
    string[] t2 = new string[t1.length]; 
    hanyupinyinoutputformat t3 = new hanyupinyinoutputformat(); 
    t3.setcasetype(hanyupinyincasetype.lowercase); 
    t3.settonetype(hanyupinyintonetype.without_tone); 
    t3.setvchartype(hanyupinyinvchartype.with_v); 
    string t4 = ""; 
    int t0 = t1.length; 
    try 
    { 
      for (int i = 0; i < t0; i++) 
      { 
        // 判断是否为汉字字符 
        if (java.lang.character.tostring(t1[i]).matches("[\\u4e00-\\u9fa5]+")) 
        { 
          t2 = pinyinhelper.tohanyupinyinstringarray(t1[i], t3); 
          t4 += t2[0]; 
        } else 
        { 
          t4 += java.lang.character.tostring(t1[i]); 
        } 
      } 
      return t4; 
    } catch (badhanyupinyinoutputformatcombination e1) 
    { 
      e1.printstacktrace(); 
    } 
    return t4; 
  } 

3、获取中文首字母缩写(如:广东省-->gds)
 

  </pre><pre name="code" class="java"><span style="white-space:pre">  </span>/** 
   * 得到中文首字母 
   * @param str 需要转化的中文字符串 
   * @return 
   */ 
  public static string getpinyinheadchar(string str) 
  { 
    string convert = ""; 
    for (int j = 0; j < str.length(); j++) 
    { 
      char word = str.charat(j); 
      string[] pinyinarray = pinyinhelper.tohanyupinyinstringarray(word); 
      if (pinyinarray != null) 
      { 
        convert += pinyinarray[0].charat(0); 
      } else 
      { 
        convert += word; 
      } 
    } 
    return convert; 
  } 

4、获取中文首字母并把转化为大写字母(如:广东省--> g)

我们需要结合步骤3 getpinyinheadchar方法,代码如下:

</pre><pre name="code" class="java"><span style="white-space:pre">    </span>string s = getpinyinheadchar("广东省"); 
    system.out.println("得到拼音首字母缩写为:" + s); 
    stringbuffer sb = new stringbuffer(s); 
    if (sb.length() > 1) 
    { 
      string ss = sb.delete(1, sb.length()).tostring(); 
      system.out.println("得到的首字母为:" 
          + character.touppercase(ss.tochararray()[0]) + ""); 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网