一瘤泪、前言
工作中有時(shí)候會(huì)遇到漢字拼音轉(zhuǎn)換的需求灶泵,例如:用戶首字母搜索某個(gè)內(nèi)容的時(shí)候,wzry 可搜索 王者榮耀相關(guān)的对途。
二惶洲、使用Pinyin4j
1、maven項(xiàng)目添加依賴包
<!-- 漢語 拼音 轉(zhuǎn)換的包-->
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>
2膳犹、漢字轉(zhuǎn)拼音工具類(具體看注釋)
package com.sam.util;
import net.sourceforge.pinyin4j.PinyinHelper;
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;
/**
* 中文漢字轉(zhuǎn)拼音工具類
*
* @author sam
* @since 2017/5/10
*/
public class PinyinUtil {
public static void main(String[] args) throws BadHanyuPinyinOutputFormatCombination {
String str = PinyinUtil.getPinYinHeadChar("小超人");
System.out.println(str);
// String[] strs = PinyinUtil.getPinYin('空');
// for (String str : strs) {
// System.out.println(str);
// }
}
/**
* 傳入中文獲取首字母 (小寫)
* 如:小超人 -> xcr
*
* @param str 需要轉(zhuǎn)化的中文字符串
* @return
*/
public static String getPinYinHeadChar(String str) {
String convert = "";
for (int j = 0; j < str.length(); j++) {
char word = str.charAt(j);
String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
if (pinyinArray != null) {
convert += pinyinArray[0].charAt(0);
} else {
convert += word;
}
}
return convert;
}
/**
* 獲取中文字的拼音(多音字恬吕,拼音后的數(shù)字代表第幾聲)
* 如:空 -> kong1 kong4
*
* @param word
* @return
*/
public static String[] getPinYin(char word) {
return PinyinHelper.toHanyuPinyinStringArray(word);
}
/**
* 獲取中文字的拼音(多音字,拼音上的符號(hào)代表第幾聲)
* 如:空 -> kōng kòng
*
* @param word
* @return
*/
public static String[] getPinYinWithToneMark(char word) throws BadHanyuPinyinOutputFormatCombination {
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
format.setToneType(HanyuPinyinToneType.WITH_TONE_MARK);
format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
return PinyinHelper.toHanyuPinyinStringArray(word, format);
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者