个人记录。
<!-- https://mvnrepository.com/artifact/com.belerweb/pinyin4j -->
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.1</version>
</dependency>
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 admin
*/
public class PinYinUtil {
private static HanyuPinyinOutputFormat defaultFormat = null;
static HanyuPinyinOutputFormat getHanyuPinyinOutputFormat() {
if (null == defaultFormat) {
defaultFormat = new HanyuPinyinOutputFormat();
}
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
return defaultFormat;
}
/**
* 获取汉字串拼音首字母,英文字符不变,特殊字符过滤
*
* @param chinese 汉字串
* @return 汉语拼音首字母
*/
public static String getFirstSpell(String chinese) {
StringBuilder firstSpell = new StringBuilder();
char[] arr = chinese.toCharArray();
for (char c : arr) {
if (c > 128) {
try {
String[] temp = PinyinHelper.toHanyuPinyinStringArray(c, getHanyuPinyinOutputFormat());
if (temp != null && temp.length >= 1) {
firstSpell.append(temp[0].charAt(0));
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
firstSpell.append(c);
}
}
return firstSpell.toString();
}
/**
* 获取汉字串拼音,英文字符不变,特殊字符过滤
*
* @param chinese 汉字串
* @return 汉语拼音
*/
public static String getFullSpell(String chinese) {
StringBuilder fullSpell = new StringBuilder();
char[] arr = chinese.toCharArray();
for (char c : arr) {
if (c > 128) {
try {
String[] temp = PinyinHelper.toHanyuPinyinStringArray(c, getHanyuPinyinOutputFormat());
if (temp != null && temp.length >= 1) {
fullSpell.append(temp[0]);
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
fullSpell.append(c);
}
}
return fullSpell.toString();
}
public static void main(String[] args) {
String fullSpell = getFullSpell("A、B1测试");
String firstSpell = getFirstSpell("A、B1测试");
System.err.println(fullSpell);
System.err.println(firstSpell);
}
}