123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- package com.hcks.cmfds.commons.util;
- import java.util.ArrayList;
- import java.util.List;
- 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;
- /**
- *
- *
- * @Author 刘厦 (liusha.information@gmail.com)
- * @Date 创建时间:2011-8-4,下午02:18:23
- * @Version 0.0.0
- *
- * 类说明:
- *
- */
- public class PinyinUtils {
-
- public static int HANZI_UNICODE_START = 0x4e00;
- public static int HANZI_UNICODE_END = 0x9fa5;
- /**
- * 取得字符串拼音的首字母 (汉字之外字符不转化)
- * @param name
- * @return
- */
- public static String getPinyinInitial(String name) {
- List<Character> cl = new ArrayList<Character>(name.length());
- HanyuPinyinOutputFormat f = new HanyuPinyinOutputFormat();
- f.setCaseType(HanyuPinyinCaseType.UPPERCASE);
- f.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
- f.setVCharType(HanyuPinyinVCharType.WITH_V);
-
- try {
-
-
- for (int i = 0; i < name.length(); i++) {
- char c = name.charAt(i);
- if (c >= HANZI_UNICODE_START && c < HANZI_UNICODE_END) {
- String[] py = PinyinHelper.toHanyuPinyinStringArray(name.charAt(i), f);
- if (py != null) {
- cl.add(py[0].charAt(0));
- }
- } else {
- cl.add(Character.toUpperCase(c));
- }
- }
- } catch (BadHanyuPinyinOutputFormatCombination e) {
-
- }
- char[] ca = new char[cl.size()];
- for (int i = 0; i < ca.length; i++) {
- ca[i] = cl.get(i);
- }
- return new String(ca);
- }
- /**
- * 取 汉字拼音全拼 (多音字只取最常用读音)
- * @param name
- * @return
- */
- public static String getPinyinComplete(String name) {
- StringBuilder result = new StringBuilder();
- HanyuPinyinOutputFormat f = new HanyuPinyinOutputFormat();
- f.setCaseType(HanyuPinyinCaseType.UPPERCASE);
- f.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
- f.setVCharType(HanyuPinyinVCharType.WITH_V);
-
- try {
- for (int i = 0; i < name.length(); i++) {
- char c = name.charAt(i);
- if (c >= HANZI_UNICODE_START && c < HANZI_UNICODE_END) {
- String[] py = PinyinHelper.toHanyuPinyinStringArray(name.charAt(i), f);
- if (py != null) {
- result.append(py[0]);
- }
- } else {
- result.append(c);
- }
- }
- } catch (BadHanyuPinyinOutputFormatCombination e) {
-
- }
- return result.toString();
- }
-
- public static void main(String[] args) {
- System.out.println(PinyinUtils.getPinyinInitial("虚空假面"));
- System.out.println(PinyinUtils.getPinyinInitial("虚空假面111"));
- System.out.println(PinyinUtils.getPinyinInitial("虚空假面11aa"));
-
- }
-
- }
|