欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2021-03-01 13:43:49|栏目:JAVA代码|点击:

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

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]) + ""); 

上一篇:云IDE:Eclipse Che:Eclipse下一代IDE(推荐)

栏    目:JAVA代码

下一篇:深入理解Java之HashMap源码剖析

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

本文地址:http://www.codeinn.net/misctech/72223.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有