随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)
介绍3个方法:汉字转换为拼音、获取每个汉字的首字母、获取第一个汉字的首字母(如果是姓名,即姓的首字母),代码如下:
PinYinUtil:
package com.home;
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;
/**
* 拼音转换工具类
*
* @author Administrator
*
*/
public class PinYinUtil {
/**
* 将字符串中的中文转化为拼音,其他字符不变
*
* @param inputStr
* @return
*/
public static String getPinYin(String inputStr) {
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
format.setVCharType(HanyuPinyinVCharType.WITH_V);
char[] input = inputStr.trim().toCharArray();
String output = "";
try {
if (input != null) {
for (char c : input) {
if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
String[] temp = PinyinHelper.toHanyuPinyinStringArray(c, format);
output += temp[0];
} else {
output += Character.toString(c);
}
}
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
}
return output;
}
/**
* 得到每个汉字首字母,英文字符不变
*
* @param chineseStr
* @return
*/
public static String getFirstSpell(String chineseStr) {
StringBuffer sb = new StringBuffer();
char[] input = chineseStr.toCharArray();
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
if (input != null) {
for (char c : input) {
if (c > 128) {
try {
String[] temp = PinyinHelper.toHanyuPinyinStringArray(c, format);
if (temp != null) {
sb.append(temp[0].charAt(0));
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
sb.append(c);
}
}
}
return sb.toString().replaceAll("\\W", "").trim();
}
/**
* 获取姓名中姓的首字母
*
* @param chineseStr
* @param isUpper
* 是否转换为大写字母
* @return
*/
public static String getFirstLetter(String chineseStr, boolean isUpper) {
String pinyin = getPinYin(chineseStr);
String firstLetter = pinyin.substring(0, 1);
if (isUpper) {
firstLetter = firstLetter.toUpperCase();
} else {
firstLetter = firstLetter.toLowerCase();
}
return firstLetter;
}
}
拼音转换需要用到的jar包地址:拼音转换工具包-Android工具类资源-CSDN下载