java 獲取字符串的拼音工具類
使用的是com.github.stuxuhai-jpinyin (GPL協議) ,感謝開源
最近閒來無事 ,就是想發篇文章, 所以寫個工具類分享一下
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 "";
}
}