java将汉字转成拼音首字母大写字母_java实现将汉字转为首字母、拼音
本文轉自java實現將漢字轉為拼音
作者itRed
本人僅稍作整理,并提出一些問題。問題的話暫時沒時間處理,等以后有時間了再更新。
測試參數
String info="漢字轉換為拼音";
結果
HZZHWPY --- 全部大寫需要.toUpperCase()
hanzizhuanhuanweipinyin
步驟
1、Maven中引入依賴
com.belerweb
pinyin4j
2.5.1
2、定義方法
/**
* 獲取字符串拼音的第一個字母
* @param chinese
* @return
*/
public static String ToFirstChar(String chinese){
String pinyinStr = "";
char[] newChar = chinese.toCharArray(); //轉為單個字符
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < newChar.length; i++) {
if (newChar[i] > 128) {
try {
pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0].charAt(0);
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
}else{
pinyinStr += newChar[i];
}
}
return pinyinStr;
}
/**
* 漢字轉為拼音
* @param chinese
* @return
*/
public static String ToPinyin(String chinese){
String pinyinStr = "";
char[] newChar = chinese.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < newChar.length; i++) {
if (newChar[i] > 128) {
try {
pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0];
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
}else{
pinyinStr += newChar[i];
}
}
return pinyinStr;
}
3、調用方法
public static void main(String[] args) {
System.out.println(ToFirstChar("漢字轉換為拼音").toUpperCase()); //轉為首字母大寫
System.out.println(ToPinyin("漢字轉換為拼音"));
}
問題
今天(2017-9-21 19:38:29)工作上有這個需求,直接把原文的代碼拿過來用了。
但是有個問題,如果字符串中有符號,那么就會報錯。
因為我的數據中符號比較簡單,都是 () ()括號之類的,所以我直接加了個簡單的判斷,使用replace把括號拿掉了,不過還是要考慮一下出現大量符號的情況。
先記錄下,以后有時間了再來處理這個。
總結
以上是生活随笔為你收集整理的java将汉字转成拼音首字母大写字母_java实现将汉字转为首字母、拼音的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【小李木耳】2012年5月高兴事:哈尔滨
- 下一篇: HTML——盒模型