xuhy
2024-12-13 2536f425d95d2e21aa1d61e942b52f10947c9300
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
38
39
40
41
42
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 "";
    }
}