package com.jeesite.modules.basetools;
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;
/**
* 汉字转拼音方法
* 可转全拼 首拼
*/
public class HanziToPinYinUtils {
public static void main(String[] args) {
System.out.println(getPinyin("中国红123")); //--zhongguohong123
System.out.println(getFirstSpell("中国红123")); //--zhongguohong123
System.out.println(getFullSpell("中国红123")); //--zhongguohong123
}
/**
* @param china (字符串 汉字)
* @return 汉字转拼音 其它字符不变
*/
public static String getPinyin(String china){
HanyuPinyinOutputFormat formart = new HanyuPinyinOutputFormat();
formart.setCaseType(HanyuPinyinCaseType.LOWERCASE);
formart.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
formart.setVCharType(HanyuPinyinVCharType.WITH_V);
char[] arrays = china.trim().toCharArray();
String result = "";
try {
for (int i=0;i<arrays.length;i++) {
char ti = arrays[i];
if(Character.toString(ti).matches("[\\u4e00-\\u9fa5]")){ //匹配是否是中文
String[] temp = PinyinHelper.toHanyuPinyinStringArray(ti,formart);
result += temp[0];
}else{
result += ti;
}
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
return result;
}
/**
* 获取汉字串拼音首字母,英文字符不变
* @param chinese 汉字串
* @return 汉语拼音首字母
*/
public static String getFirstSpell(String chinese) {
StringBuffer pybf = new StringBuffer();
char[] arr = chinese.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < arr.length; i++) {
if (arr[i] > 128) {
try {
String[] temp = PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat);
if (temp != null) {
pybf.append(temp[0].charAt(0));
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
pybf.append(arr[i]);
}
}
return pybf.toString().replaceAll("\\W", "").trim().toUpperCase();
}
/**
* 获取汉字串拼音,英文字符不变
* @param chinese 汉字串
* @return 汉语拼音
*/
public static String getFullSpell(String chinese) {
StringBuffer pybf = new StringBuffer();
char[] arr = chinese.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < arr.length; i++) {
if (arr[i] > 128) {
try {
pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]);
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
pybf.append(arr[i]);
}
}
return pybf.toString();
}
}
依赖包:
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>
运行图: