import net.sourceforge.pinyin4j.*;app
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;ide
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;ui
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;spa
public class Pinyinorm
{字符串
public static void main(String[] args)get
{ it
Hanyu hanyu = new Hanyu();io
String str = "咱們";form
String strPinyin = hanyu.getStringPinYin(str);
System.out.println(strPinyin);
}
}
class Hanyu
{
private HanyuPinyinOutputFormat format = null;
private String[] pinyin;
public Hanyu()
{
format = new HanyuPinyinOutputFormat();
//WITH_TONE_NUMBER是輸出拼音的音調
//WITHOUT_TONE 是沒有輸出音調
format.setToneType(HanyuPinyinToneType.WITH_TONE_NUMBER);
// format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
pinyin = null;
}
//轉換單個字符
public String getCharacterPinYin(char c)
{
try
{
pinyin = PinyinHelper.toHanyuPinyinStringArray(c, format);
}
catch(BadHanyuPinyinOutputFormatCombination e)
{
e.printStackTrace();
}
// 若是c不是漢字,toHanyuPinyinStringArray會返回null
if(pinyin == null) return null;
// 只取一個發音,若是是多音字,僅取第一個發音
return pinyin[0];
}
//轉換一個字符串
public String getStringPinYin(String str)
{
StringBuilder sb = new StringBuilder();
String tempPinyin = null;
for(int i = 0; i < str.length(); ++i)
{
tempPinyin =getCharacterPinYin(str.charAt(i));
if(tempPinyin == null)
{
// 若是str.charAt(i)非漢字,則保持原樣
sb.append(str.charAt(i));
}
else
{
sb.append(tempPinyin);
}
}
return sb.toString();
}
}