/** * 提取汉字首字母工具类 */ public class ChineseToFirstLetterUtil { /** * 汉字转拼音大写首字母 * * @param c * @return */ public static String ChineseToFirstLetter(String c) { StringBuilder string = new StringBuilder(); char b; int a = c.length(); for (int k = 0; k < a; k++) { b = c.charAt(k); String d = String.valueOf(b); String str = converterToFirstSpell(d); String s = str.toUpperCase(); String g = s; char h; for (int y = 0; y <= 0; y++) { h = g.charAt(0); string.append(h); } } return string.toString(); }
/** * 汉子转拼音 * * @param chines * @return */ public static String converterToFirstSpell(String chines) { StringBuilder pinyinName = new StringBuilder(); char[] nameChar = chines.toCharArray(); HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE); defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); for (int i = 0; i < nameChar.length; i++) { String s = String.valueOf(nameChar[i]); if (s.matches("[\\u4e00-\\u9fa5]")) { try { String[] mPinyinArray = PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat); pinyinName.append(mPinyinArray[0]); } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } } else { pinyinName.append(nameChar[i]); } } return pinyinName.toString(); }
public static void main(String[] args) { System.out.println(ChineseToFirstLetter("干饭人干饭魂干饭都是人上人")); System.out.println(converterToFirstSpell("今日干饭不狠,明日地位不稳")); } }