package com.yqzx.common.util;
|
|
// @formatter:off
|
|
import lombok.extern.slf4j.Slf4j;
|
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;
|
|
/**
|
* .-~~~~~~~~~-._ _.-~~~~~~~~~-.
|
* __.' @Author ~. .~ 代码无Bug `.__
|
* .'// liu.q \./ (秘籍) \\`.
|
* .'// [916000612@qq.com] | 欲练神功 引刀自宫 \\`.
|
* .'// .-~"""""""~~~~-._ | _,-~~~~"""""""~-. \\`.
|
* .'//.-" 2019-04-10 `-. | .-' 17:35 "-.\\`.
|
* .'//______.============-.. \ | / ..-============.______\\`.
|
*.'______________________________\|/______________________________`.
|
*
|
* @Description :
|
*/
|
// @formatter:on
|
@Slf4j
|
public class Pinyin {
|
|
|
/**
|
* 获取字符串拼音的第一个字母
|
*
|
* @param chinese
|
* @return
|
*/
|
public static String ToFirstChar(String chinese) {
|
String pinyinStr = "";
|
char[] newChar = chinese.toCharArray(); //转为单个字符
|
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
|
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
|
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
|
for (int i = 0; i < newChar.length; i++) {
|
if (newChar[i] > 128) {
|
try {
|
pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0].charAt(0);
|
} catch (BadHanyuPinyinOutputFormatCombination e) {
|
log.error(e.getMessage());
|
}
|
} else {
|
pinyinStr += newChar[i];
|
}
|
}
|
return pinyinStr;
|
}
|
|
/**
|
* 汉字转为拼音
|
*
|
* @param chinese
|
* @return
|
*/
|
public static String ToPinyin(String chinese) {
|
String pinyinStr = "";
|
char[] newChar = chinese.toCharArray();
|
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
|
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
|
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
|
for (int i = 0; i < newChar.length; i++) {
|
if (newChar[i] > 128) {
|
try {
|
pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0];
|
} catch (BadHanyuPinyinOutputFormatCombination e) {
|
log.error(e.getMessage());
|
}
|
} else {
|
pinyinStr += newChar[i];
|
}
|
}
|
return pinyinStr;
|
}
|
}
|