package com.mvc.utils;

import net.sourceforge.pinyin4j.PinyinHelper;

public class PinyinUtil {
    /**
     * 提取汉字的拼音首字母
     * @param chinese 汉字字符串
     * @param removeSpecialChars 是否去除特殊符号
     * @return 拼音首字母组成的字符串
     */
    public static String getPinYinHeadChar(String chinese, boolean removeSpecialChars) {
        StringBuilder sb = new StringBuilder();
        for (char c : chinese.toCharArray()) {
            if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) { // 判断是否为汉字
                String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c);
                if (pinyinArray != null) {
                    sb.append(pinyinArray[0].charAt(0));
                }
            } else if (!removeSpecialChars || Character.isLetterOrDigit(c)) {
                sb.append(c); // 非汉字字符且不去除特殊符号或字符是字母或数字时直接添加
            }
        }
        return sb.toString().toUpperCase();
    }

    public static void main(String[] args) {
        String chinese = "密云区西田各庄镇疃里村村委会院内饮水井Num-1";
        System.out.println(getPinYinHeadChar(chinese,false));
    }
}
