汉字转拼音的工具类
  onf2Mh1AWJAW 2023年11月01日 65 0

平常是处理文字的时候更多用到的是字符串方面的工具类,作为学习汉字的工具,拼音还是很重要的一个辅助方式,分享一个汉字转拼音的工具类。可以用于帮助学习汉字或者作为一些汉字的辅助说明都也是可以的。这个还支持将汉字拼音输出为首字母,例如"愷龍"可以输出为"kl",在现在大家很多时候都用缩写的情况下,可以也可以作为一个辅助的工具。

该工具类用到了pinyin4j-2.5.0.jar包

包下载地址:
网盘下载:https://kohler.lanzouv.com/i3bQG0g2imkj

Maven中央库:https://mvnrepository.com/artifact/org.clojars.cbilson/pinyin4j/2.5.0
完整代码:


import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;


public class GetPinyin {

   /**
    * 得到 全拼
    * @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);
       StringBuffer t4 = new StringBuffer();
       int t0 = t1.length;
       try {
           for (char c : t1) {
               // 判断是否为汉字字符
               if (Character.toString(c).matches(
                       "[\\u4E00-\\u9FA5]+")) {
                   t2 = PinyinHelper.toHanyuPinyinStringArray(c, t3);
                   t4.append(t2[0]);
               } else {
                   t4.append(Character.toString(c));
               }
           }
           return t4.toString();
       } catch (BadHanyuPinyinOutputFormatCombination e1) {
           e1.printStackTrace();
       }
       return t4.toString();
   }

   /**
    * 得到中文首字母
    * @param str
    * @return
    */
   public static String getPinYinHeadChar(String str) {

       StringBuffer convert = new StringBuffer();
       for (int j = 0; j < str.length(); j++) {
           char word = str.charAt(j);
           String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
           if (pinyinArray != null) {
               convert.append(pinyinArray[0].charAt(0));
           } else {
               convert.append(word);
           }
       }
       return convert.toString();
   }


   public static void main(String[] args) {

       String cnStr = "快关注愚生浅末";
       System.out.println(getPingYin(cnStr));
       System.out.println(getPinYinHeadChar(cnStr));
   }

}

运行效果:
image
公众号原文地址:https://mp.weixin.qq.com/s/K0tBRnV0X8yy2OJY5Okt-A

欢迎关注公众号:愚生浅末。

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

上一篇: day02-实现01 下一篇: Spring注解开发
  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
onf2Mh1AWJAW