当前位置: 首页 > 工具软件 > Pinyin4Net > 使用案例 >

使用pinyin4j获取汉字的首字母

汝跃
2023-12-01

pom文件中引入pinyin4j包

        <dependency>
            <groupId>com.belerweb</groupId>
            <artifactId>pinyin4j</artifactId>
            <version>2.5.0</version>
        </dependency>

使用导入的包,调用方法进行汉字的首字母获取

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 net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public static String getFirstPinYin(String hanyu) {
	HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
	format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
	format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

	StringBuilder firstPinyin = new StringBuilder();
	char[] hanyuArr = hanyu.trim().toCharArray();
	try {
		for (int i = 0, len = hanyuArr.length; i < len; i++) {
			if(Character.toString(hanyuArr[i]).matches("[\\u4E00-\\u9FA5]+")){
				String[] pys = PinyinHelper.toHanyuPinyinStringArray(hanyuArr[i],format);
				firstPinyin.append(pys[0].charAt(0));
			}else {
				firstPinyin.append(hanyuArr[i]);
			}
		}
	} catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
		badHanyuPinyinOutputFormatCombination.printStackTrace();
	}
	return firstPinyin.toString();
}
 类似资料: