package com.ruoyi.web.controller.tool; import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; public class PinyinExample { public static void main(String[] args) { String chineseString = "四川省"; String firstLetter = getFirstLetter(chineseString); System.out.println("First letter of '" + chineseString + "' is: " + firstLetter); } public static String getFirstLetter(String chinese) { HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat(); format.setCaseType(HanyuPinyinCaseType.LOWERCASE); format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); if (chinese == null || chinese.isEmpty()) { return ""; } char firstChar = chinese.charAt(0); if (Character.toString(firstChar).matches("[\\u4E00-\\u9FA5]+")) { try { String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(firstChar, format); if (pinyinArray != null && pinyinArray.length > 0) { return pinyinArray[0].substring(0, 1).toUpperCase(); } } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } } else { return Character.toString(firstChar).toUpperCase(); } return ""; } }