汉字转拼音

第一步:引入jar包

<dependency>
    <groupId>com.belerweb</groupId>
    <artifactId>pinyin4j</artifactId>
    <version>2.5.0</version>
</dependency>

第二步:编写实现代码

 1 import net.sourceforge.pinyin4j.PinyinHelper;
 2 import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
 3 import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
 4 import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
 5 import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
 6 import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
 7 /**
 8  * 汉字转拼音
 9  * @author zhengchangjie  
10  * @date 2019年2月28日
11  */
12 public class PinYin {
13 
14     /**
15      * 得到 全拼
16      * @param src
17      * @return
18      */
19     public static String getPingYin(String src) {
20         char[] t1 = null;
21         t1 = src.toCharArray();
22         String[] t2 = new String[t1.length];
23         HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
24         t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
25         t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
26         t3.setVCharType(HanyuPinyinVCharType.WITH_V);
27         String t4 = "";
28         int t0 = t1.length;
29         try {
30             for (int i = 0; i < t0; i++) {
31                 // 判断是否为汉字字符
32                 if (java.lang.Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {
33                     t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);
34                     t4 += t2[0];
35                 } else {
36                     t4 += java.lang.Character.toString(t1[i]);
37                 }
38             }
39             return t4;
40         } catch (BadHanyuPinyinOutputFormatCombination e1) {
41             e1.printStackTrace();
42         }
43         return t4;
44     }
45 
46     /**
47      * 得到中文首字母
48      * 
49      * @param str
50      * @return
51      */
52     public static String getPinYinHeadChar(String str) {
53 
54         String convert = "";
55         for (int j = 0; j < str.length(); j++) {
56             char word = str.charAt(j);
57             String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
58             if (pinyinArray != null) {
59                 convert += pinyinArray[0].charAt(0);
60             } else {
61                 convert += word;
62             }
63         }
64         return convert;
65     }
66 
67     /**
68      * 将字符串转移为ASCII码
69      * 
70      * @param cnStr
71      * @return
72      */
73     public static String getCnASCII(String cnStr) {
74         StringBuffer strBuf = new StringBuffer();
75         byte[] bGBK = cnStr.getBytes();
76         for (int i = 0; i < bGBK.length; i++) {
77             // System.out.println(Integer.toHexString(bGBK[i]&0xff));
78             strBuf.append(Integer.toHexString(bGBK[i] & 0xff));
79         }
80         return strBuf.toString();
81     }
82 }

 

 

posted @ 2019-03-01 16:11  麦田守护梦  阅读(194)  评论(0编辑  收藏  举报