一、前言
基于belerweb的pinyin4j-2.5.0.jar依赖包,定义ChineseWordsFirstLetterUtil工具类实现获取拼音首字母,如“犯我中华者虽远必诛!”获取结果“FWZHZSYBZ!”
二、代码示例
pom依赖配置
<dependency>@b@ <groupId>com.belerweb</groupId>@b@ <artifactId>pinyin4j</artifactId>@b@ <version>2.5.0</version>@b@</dependency>
代码示例
package com.xwood.gw.util;@b@@b@import net.sourceforge.pinyin4j.PinyinHelper;@b@import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;@b@import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;@b@import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;@b@import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;@b@@b@public class ChineseWordsFirstLetterUtil {@b@@b@ public static String ChineseToFirstLetter(String c) {@b@ String string = "";@b@ char b;@b@ int a = c.length();@b@ for (int k = 0; k < a; k++) {@b@ b = c.charAt(k);@b@ String d = String.valueOf(b);@b@ String str = converterToFirstSpell(d);@b@ String s = str.toUpperCase();@b@ String g = s;@b@ char h;@b@ int j = g.length();@b@ for (int y = 0; y <= 0; y++) {@b@ h = g.charAt(0);@b@ string += h;@b@ }@b@ }@b@ return string;@b@ }@b@@b@ public static String converterToFirstSpell(String chines) {@b@ String pinyinName = "";@b@ char[] nameChar = chines.toCharArray();@b@ HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();@b@ defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);@b@ defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);@b@ for (int i = 0; i < nameChar.length; i++) {@b@ String s = String.valueOf(nameChar[i]);@b@ if (s.matches("[\\u4e00-\\u9fa5]")) {@b@ try {@b@ String[] mPinyinArray = PinyinHelper@b@ .toHanyuPinyinStringArray(nameChar[i],@b@ defaultFormat);@b@ pinyinName += mPinyinArray[0];@b@ } catch (BadHanyuPinyinOutputFormatCombination e) {@b@ e.printStackTrace();@b@ }@b@ } else {@b@ pinyinName += nameChar[i];@b@ }@b@ }@b@ return pinyinName;@b@ }@b@@b@ public static void main(String[] args) {@b@ System.err.println(ChineseToFirstLetter("犯我中华者虽远必诛!"));@b@ }@b@@b@}
控制台打印结果
FWZHZSYBZ!