java漢字轉換為拼音首字母
阿新 • • 發佈:2019-01-04
今天講講如何把中文的漢字轉換為拼音首字母,如"中國"轉換為“zg”,這裡要用到一個開源jar包【pinyin4j】
<span style="font-size:14px;">import net.sourceforge.pinyin4j.PinyinHelper; /** * 漢字轉換為拼音首字母 * @author Strong * */ public class WordToPinYin { public static String toPinyin(String str){ String convert = ""; for (int j = 0, int len = str.length(); j < len; j++) { char word = str.charAt(j); String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word); if (pinyinArray != null) { convert += pinyinArray[0].charAt(0); } else { convert += word; } } return convert; } }</span>
<span style="font-size:14px;">public static void main(String[] args){</span>
<span style="font-size:14px;"> String hzStr = "拼音";</span>
<span style="font-size:14px;"> System.out.printf(WordToPinYin.toPinyin(hzStr));</span>
<span style="font-size:14px;">}</span>