Sometimes we encounter this situation, and we need to obtain certain Chinese pinyin, Chinese abbreviations and Chinese initials. Below I will introduce to you how to obtain Chinese pinyin abbreviations.
1. Project establishment and configuration
First, we create a Java project, create a new libs folder and introduce a 734a7099-4830-39f2-a136-0e850ccdcc7a.jar file. I believe that this step is not necessary to be written in detail, skip it.
2. Obtain Chinese pinyin (such as: Guangdong Province-->guangdongsheng)
</pre><pre name="code"><span style="white-space:pre"> </span>/** * Get the full Chinese spelling* @param src The Chinese string that needs to be converted* @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++) { // Determine whether it is a Chinese character 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. Obtain the abbreviation of Chinese acronyms (such as: Guangdong Province-->gds)
</pre><pre name="code"><span style="white-space:pre"> </span>/** * Get the Chinese initial letter* @param str The Chinese string that needs to be converted* @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. Get the Chinese initial letter and convert it into capital letters (such as: Guangdong Province-->G)
We need to combine step 3 getPinYinHeadChar method, the code is as follows:
</pre><pre name="code"><span style="white-space:pre"> </span>String s = getPinYinHeadChar("Guangdong Province"); System.out.println("Get the pinyin abbreviation: " + s); StringBuffer sb = new StringBuffer(s); if (sb.length() > 1) { String ss = sb.delete(1, sb.length()).toString(); System.out.println("Get the initial letter: " + Character.toUpperCase(ss.toCharArray()[0]) + "");The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.