POM依赖:
<dependency> <groupId>com.belerweb</groupId> <artifactId>pinyin4j</artifactId> <version>2.5.1</version> </dependency>
代码:
HanyuPinyinCaseType.UPPERCASE private String getFirstLetters(String ChineseLanguage, HanyuPinyinCaseType caseType) { char[] cl_chars = ChineseLanguage.trim().toCharArray(); String hanyupinyin = ""; HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); defaultFormat.setCaseType(caseType); defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); try { for(int i = 0; i < cl_chars.length; ++i) { String str = String.valueOf(cl_chars[i]); if (str.matches("[一-龥]+")) { hanyupinyin = hanyupinyin + PinyinHelper.toHanyuPinyinStringArray(cl_chars[i], defaultFormat)[0].substring(0, 1); } else if (str.matches("[0-9]+")) { hanyupinyin = hanyupinyin + cl_chars[i]; } else if (str.matches("[a-zA-Z]+")) { hanyupinyin = hanyupinyin + cl_chars[i]; } else { hanyupinyin = hanyupinyin + cl_chars[i]; } } } catch (BadHanyuPinyinOutputFormatCombination var7) { System.out.println("字符不能转成汉语拼音"); } return hanyupinyin; }
单字符一个一个转换