简介:
由于第三方需要人员姓名的拼音格式,特此将姓名转为拼音,并首字母大写
实现:
所需maven依赖:
<!--拼音--> <!-- https://mvnrepository.com/artifact/com.belerweb/pinyin4j --> <dependency> <groupId>com.belerweb</groupId> <artifactId>pinyin4j</artifactId> <version>2.5.1</version> </dependency>
/** * 获取字符串内的所有汉字的汉语拼音并大写每个字的首字母 * * @param chinese * @return */ public static String chineseToSpell(String chinese) { if (chinese == null) { return null; } HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat(); //小写 format.setCaseType(HanyuPinyinCaseType.LOWERCASE); // 不标声调 format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); // u:的声母替换为v format.setVCharType(HanyuPinyinVCharType.WITH_V); try { StringBuilder stringBuilder = new StringBuilder(); int chineseLength = chinese.length(); for (int num = 0; num < chineseLength; num++) { String[] array = PinyinHelper.toHanyuPinyinStringArray(chinese.charAt(num), format); if (array == null || array.length == 0) { continue; } // 不管多音字,只取第一个 String str = array[0]; // 获取拼音第一个字母 char firstCharacter = str.charAt(0); String pinyin; if (num == 0) { pinyin = String.valueOf(firstCharacter).toUpperCase().concat(str.substring(1)); } else { pinyin = String.valueOf(firstCharacter).concat(str.substring(1)); } stringBuilder.append(pinyin); } return stringBuilder.toString(); } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } return null; }
测试:
目前存在的问题:对于多音字来说目前是只取第一个发音