我們有時(shí)候會(huì)遇到這樣的情況,需要獲取某些中文的拼音、中文首字母縮寫(xiě)和中文首字母,下面我將為大家介紹一下如何獲取中文拼音的縮寫(xiě)。
1、項(xiàng)目建立和配置
首先,我們建立一個(gè)Java項(xiàng)目,新建libs文件夾并引入一個(gè)734a7099-4830-39f2-a136-0e850ccdcc7a.jar文件,這個(gè)步驟相信就不用詳細(xì)寫(xiě)了,跳過(guò)。
2、獲取中文拼音(如:廣東省 -->guangdongsheng)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
</pre><pre name= "code" class = "java" ><span style= "white-space:pre" > </span> /** * 得到中文全拼 * @param src 需要轉(zhuǎn)化的中文字符串 * @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、獲取中文首字母縮寫(xiě)(如:廣東省-->gds)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
</pre><pre name= "code" class = "java" ><span style= "white-space:pre" > </span> /** * 得到中文首字母 * @param str 需要轉(zhuǎn)化的中文字符串 * @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、獲取中文首字母并把轉(zhuǎn)化為大寫(xiě)字母(如:廣東省--> G)
我們需要結(jié)合步驟3 getPinYinHeadChar方法,代碼如下:
1
2
3
4
5
6
7
8
|
</pre><pre name= "code" class = "java" ><span style= "white-space:pre" > </span>String s = getPinYinHeadChar( "廣東省" ); System.out.println( "得到拼音首字母縮寫(xiě)為:" + 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 ]) + "" ); |
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。