java 獲取字符串的拼音工具包的使用
使用的是com.github.stuxuhai-jpinyin (GPL協議) ,感謝開源
最近閒來無事 ,發現一個好東西, 就是github上的 jpinyin
然而, 工具包的作者的 https://github.com/stuxuhai/jpinyin 並不能訪問, 是404 , 且該包2016年後已經無維護更新了(mvn倉庫中)
如果有其他相似的包, 可以留言, 方便看到這篇文章的其他人
這個包可以獲取漢字的拼音, 還有音標哦
jpinyin核心類: PinyinHelper
<dependency>
<groupId>com.github.stuxuhai</groupId>
<artifactId>jpinyin</artifactId>
<version>1.1.8</version>
</dependency>
public class PinyinUtil {
/**
* 獲取str的拼音. ,全小寫,無音標
* <pre>
* null => ""
* "09" => "09"
* " as哈" => "asha"
* "重樓" => "zhongchonglou"
* </pre>
*
* @param str 要轉換成拼音的字符串,Nullable,特殊字符也行
* @return str的拼音, 全小寫, 無音標
*/
public static String toPinyin(@Nullable String str) {
return toPinyin(str, null);
}
/**
* 獲取str的拼音. ,全小寫,無音標
* <pre>
* null => ""
* "" => ""
* " as哈" => "asha"
* "重樓" => "zhongchonglou"
* </pre>
*
* @param str 要轉換成拼音的字符串,Nullable,特殊字符也行
* @param length 返回的string的最大長度.安全,無異常.
* @return str 的拼音,全小寫,無音標, 且 str.length <= length
*/
public static String toPinyin(@Nullable String str, Integer length) {
String s = StringUtils.replace(str, " ", "");
if (StringUtils.isBlank(s)) {
return StringUtils.EMPTY;
}
char[] chars = s.toCharArray();
StringBuilder sb = new StringBuilder(str.length() * 5);
for (char c : chars) {
String[] strings = PinyinHelper.convertToPinyinArray(c, PinyinFormat.WITHOUT_TONE);
sb.append(strings.length == 0 ? c : StringUtils.join(strings));
}
String result = sb.toString();
if (length != null) {
result = StringUtils.substring(result, 0, length);
}
return result;
}
/**
* 獲取拼音首字母縮略詞, 全小寫.
* <pre>
* null => ""
* "" => ""
* "12" => "12"
* "重樓" => "zcl"
* </pre>
*
* @param str 傳什麼都行
* @param length 返回拼音首字母縮略詞的的最大長度
* @return 縮拼音首字母略詞
*/
public static String toShortPinyin(@Nullable String str, Integer length) {
str = StringUtils.trimToEmpty(str);
if (!StringUtils.isBlank(str)) {
try {
String shortPinyin = PinyinHelper.getShortPinyin(str);
if (length != null) {
return StringUtils.substring(shortPinyin, 0, length);
} else {
return shortPinyin;
}
} catch (PinyinException e) {
return StringUtils.EMPTY;
}
}
return "";
}
}