功能:
根據(jù) PinyinType 類型指定要獲取的是全拼或者拼音首字母
依賴:
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>
源碼:
package com.dotions.utils;
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 Pinyin4JUtil {
private Pinyin4JUtil() {
}
public enum PinyinType {
FULL, HEAD
}
private static HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
static {
// 格式化為小寫字母
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
// 不需要音調(diào)
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
// 設(shè)置對拼音字符 ü 的處理
format.setVCharType(HanyuPinyinVCharType.WITH_V);
}
/**
* 獲取漢字串拼音练慕,英文字符不變
*
* @param chinese
* 漢字串
* @return 漢語拼音
*/
public static String toPinyin(String chinese, PinyinType type) {
if (chinese == null || chinese.isEmpty()) {
return "";
} else {
StringBuilder pybf = new StringBuilder();
// 英文字母不需要轉(zhuǎn)換
char[] chars = chinese.trim().toCharArray();
String[] str = null;
for (char ch : chars) {
// 漢字的編碼是兩個(gè)字節(jié)
if (ch <= 128) {
// 英文字母或者特殊字符
pybf.append(toUpperCaseAscii(ch));
continue;
}
try {
str = PinyinHelper.toHanyuPinyinStringArray(ch, format);
// 不是漢字,估計(jì)是特殊字符
if (str == null || str.length == 0) {
pybf.append(ch);
continue;
}
// 多音字只要第一個(gè)讀音
String value = str[0];
Object obj = PinyinType.HEAD.equals(type) ? value.charAt(0) : value;
pybf.append(obj);
} catch (BadHanyuPinyinOutputFormatCombination e) {
// 出現(xiàn)格式化異常技掏,則直接添加原字符
pybf.append(ch);
}
}
return pybf.toString();
}
}
/**
* 將字符中的小寫英文字母轉(zhuǎn)為大寫
*
* @param ch
* 字符
*/
private static char toUpperCaseAscii(char ch) {
if (ch >= 97 && ch <= 122) {
return (char) (ch - 32);
} else {
return ch;
}
}
public static void main(String[] args) {
System.out.println(toPinyin("水溶布料", PinyinType.FULL));
}
}