借助开源库com.belerweb:pinyin4j:2.5.0来实现汉字转拼音。
返回结果分两种类型汉字全拼或拼音首字母
具体内容见一下代码
1.首先需要引入pinyin4j的包
compile 'com.belerweb:pinyin4j:2.5.0
2.定义工具类具体实现
如代码中使用到其他库,请自行引入
/**
* 返回拼音类型:全拼
*/
public static final String RET_PINYIN_TYPE_FULL = "full";
/**
* 返回拼音类型:首字母
*/
public static final String RET_PINYIN_TYPE_HEADCHAR = "headChar";
/**
* 字符串转换为拼音
*
* @param src 需要转换的字符串
* @param retType 返回拼音结果类型
*/
public static String str2Pinyin(String src, String retType) {
if (src != null && !"".equalsIgnoreCase(src.trim())) {
char[] srcChar = src.toCharArray();
// 汉语拼音格式输出类
HanyuPinyinOutputFormat hanYuPinOutputFormat = new HanyuPinyinOutputFormat();
// 输出设置,大小写,音标方式等
hanYuPinOutputFor