java 中文转拼音工具类
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 中文转拼音工具类相关的知识,希望对你有一定的参考价值。
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;
/**
* TODO: 请添加描述
*
* @author EX-GONGDAOSHUN700
* @date 2017/8/24
* @since 1.0.0
*/
public class ChineseToEnglish {
public ChineseToEnglish() {
}
/**
* 中文转拼音
* @param src
* @return
*/
public static String getPingYin(String src) {
Object t1 = null;
char[] var8 = src.toCharArray();
String[] t2 = new String[var8.length];
HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
t3.setVCharType(HanyuPinyinVCharType.WITH_V);
String t4 = "";
int t0 = var8.length;
try {
for (int e1 = 0; e1 < t0; ++e1) {
if (Character.toString(var8[e1]).matches("[\\u4E00-\\u9FA5]+")) {
t2 = PinyinHelper.toHanyuPinyinStringArray(var8[e1], t3);
t4 = t4 + t2[0];
} else {
t4 = t4 + Character.toString(var8[e1]);
}
}
return t4;
} catch (BadHanyuPinyinOutputFormatCombination var7) {
var7.printStackTrace();
return t4;
}
}
/**
* 中文转拼音头
* @param str
* @return
*/
public static String getPinYinHeadChar(String str) {
String convert = "";
for (int j = 0; j < str.length(); ++j) {
char word = str.charAt(j);
String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
if (pinyinArray != null) {
convert = convert + pinyinArray[0].charAt(0);
} else {
convert = convert + word;
}
}
return convert;
}
public static String getCnASCII(String cnStr) {
StringBuffer strBuf = new StringBuffer();
byte[] bGBK = cnStr.getBytes();
for (int i = 0; i < bGBK.length; ++i) {
strBuf.append(Integer.toHexString(bGBK[i] & 255));
}
return strBuf.toString();
}
public static void main(String[] args) {
String ch = getPingYin("中国");
System.out.println(ch);
}
}
以上是关于java 中文转拼音工具类的主要内容,如果未能解决你的问题,请参考以下文章