java获取中文字的首字母

时间:2022-08-22 08:05:35
package com.apps.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;

import org.apache.commons.lang.StringUtils;

public class PinyinUtil {

	public static String getPinYin(String inputString, boolean firstWord) {
		HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();

		format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);

		char[] input = inputString.trim().toCharArray();
		StringBuilder output = new StringBuilder("");

		for (int i = 0; i < input.length; i++) {
			if (ChineseUtil.isChinese(input[i])) {
				try {
					if (firstWord) {
						output.append(PinyinHelper.toHanyuPinyinStringArray(input[i], format)[0].charAt(0));
					} else {
						output.append(PinyinHelper.toHanyuPinyinStringArray(input[i], format)[0]);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				output.append(Character.toString(input[i]));
			}
		}

		return StringUtils.trim(output.toString());
	}
	
	public static void main(String[] args) {
		System.out.println(PinyinUtil.getPinYin("赵电已婚已育", true));
	}

}