5 changed files with 91 additions and 1 deletions
@ -0,0 +1,45 @@ |
|||||
|
package cc.hiver.core.common.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.exception.BadHanyuPinyinOutputFormatCombination; |
||||
|
|
||||
|
public class PinYinUtils { |
||||
|
/** |
||||
|
* 获取汉字串拼音首字母,英文字符不变 |
||||
|
* @param chinese 汉字串 |
||||
|
* @return 汉语拼音首字母 |
||||
|
*/ |
||||
|
public static String getFirstSpell(String chinese) { |
||||
|
if(chinese == null || "".equals(chinese)) { |
||||
|
return ""; |
||||
|
} |
||||
|
StringBuffer pybf = new StringBuffer(); |
||||
|
char[] arr = chinese.toCharArray(); |
||||
|
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); |
||||
|
defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE); |
||||
|
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); |
||||
|
for (int i = 0; i < arr.length; i++) { |
||||
|
if (arr[i] > 128) { |
||||
|
try { |
||||
|
String[] temp = PinyinHelper.toHanyuPinyinStringArray(arr[i]); |
||||
|
if (temp != null) { |
||||
|
pybf.append(temp[0].charAt(0)); |
||||
|
} |
||||
|
} catch (Exception e) { |
||||
|
e.printStackTrace(); |
||||
|
} |
||||
|
} else { |
||||
|
pybf.append(arr[i]); |
||||
|
} |
||||
|
} |
||||
|
return pybf.toString().replaceAll("\\W", "").trim(); |
||||
|
} |
||||
|
|
||||
|
public static void main(String[] args) { |
||||
|
System.out.println(getFirstSpell("王富康")); |
||||
|
} |
||||
|
|
||||
|
} |
||||
Loading…
Reference in new issue