zhihuifan

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

1.导入maven依赖

1 <!-- https://mvnrepository.com/artifact/com.belerweb/pinyin4j -->
2         <dependency>
3             <groupId>com.belerweb</groupId>
4             <artifactId>pinyin4j</artifactId>
5             <version>2.5.1</version>
6         </dependency>

 2.相关代码  

 1 package com.wisdragon.utils;
 2 
 3 import net.sourceforge.pinyin4j.PinyinHelper;
 4  
 5 public class HzPyUtil {
 6     /**
 7      * 得到中文汉字的首字母
 8      * @param str
 9      * @return
10      */
11     public static String getPinYinHeadChar(String str) {
12         String convert = "";
13         for (int j = 0; j < str.length(); j++) {
14             char word = str.charAt(j);
15             String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
16             if (pinyinArray != null) {
17                 convert += pinyinArray[0].charAt(0);
18             } else {
19                 convert += word;
20             }
21         }
22         return convert;
23     }
24 
25 
26      public static void main(String[] args) {
27 //        String str="你好/世界";
28        String str="中 国 人 民 解 放 军";
29         if(str.contains("/")){
30             String[] split = str.split("/");
31             String s2="";
32             for (String s:split) {
33                 System.out.println("===="+s);
34                 String s1 = HzPyUtil.getPinYinHeadChar(s)
35                         .replaceAll("\\s*", "")
36                         .substring(0, 1)
37                         .toUpperCase();
38                 s2=s2+s1;
39             }
40             System.out.println("s2==="+s2);
41         }else{
42             String s = HzPyUtil.getPinYinHeadChar(str)
43                     .replaceAll("\\s*", "")
44                     .substring(0, 2)
45                     .toUpperCase();
46             System.out.println(s);
47         }
48     }
49 }

 

 

声明:此博客为个人学习之用,如与其他作品雷同,纯属巧合,转载请指明出处!

posted on 2019-07-24 14:32  Hi,ZHF  阅读(816)  评论(0)    收藏  举报