第三方架包下載地址:https://sourceforge.net/projects/pinyin4j/files/
package a;
import java.util.LinkedList;
import java.util.regex.Pattern;
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 HanyuPinyinHelper {
/**
* 將文字轉爲漢語拼音
* @param chineselanguage 要轉成拼音的中文
*/
public String toHanyuPinyin(String ChineseLanguage){
char[] cl_chars = ChineseLanguage.trim().toCharArray();
StringBuffer hanyupinyin = new StringBuffer(); // 拼音
StringBuffer number = new StringBuffer(); // 數字
LinkedList<String> linkedList = new LinkedList<>();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);// 輸出拼音全部小寫
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 不帶聲調
defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V) ;
try {
for (int i=0; i<cl_chars.length; i++){
if (String.valueOf(cl_chars[i]).matches("[\u4e00-\u9fa5]+")){// 如果字符是中文,則將中文轉爲漢語拼音
// hanyupinyin += PinyinHelper.toHanyuPinyinStringArray(cl_chars[i], defaultFormat)[0];
linkedList.add(PinyinHelper.toHanyuPinyinStringArray(cl_chars[i], defaultFormat)[0]);
} else {// 如果字符不是中文,則不轉換
//hanyupinyin += cl_chars[i];
// linkedList.add();
if (Pattern.matches("\\d+", String.valueOf(cl_chars[i]))) {
number.append(String.valueOf(cl_chars[i]));
}
}
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
System.out.println("字符不能轉成漢語拼音");
}
for (int i = linkedList.size() -1 ; i >= 0; i--) {
hanyupinyin.append(linkedList.get(i)+".");
}
String fullStr = hanyupinyin.toString().substring(0 , hanyupinyin.length() -1);
return fullStr + number;
}
public static void main(String[] args) {
HanyuPinyinHelper hanyuPinyinHelper = new HanyuPinyinHelper() ;
System.out.print(hanyuPinyinHelper.toHanyuPinyin("鑫淼焱犇驫樸"));
}
}
運行結果:
po.biao.ben.yan.miao.xin123