汉字转拼音

先导入pinyin4j-2.5.0.jar包


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.exception.BadHanyuPinyinOutputFormatCombination;

public class Pinyin
{
	public static void main(String[] args)
	{
		Pinyin py = new Pinyin();
		String pinyin = py.HanyuToPinyin("中国人ǖη★");
		System.out.println(pinyin);
	}

	// 汉语转拼音的方法
	public String HanyuToPinyin(String name)
	{

		String pinyinName = "";
		char[] nameChar = name.toCharArray();
		
		//格式设置器
		HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
		defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		
		//循环每个字符
		for (int i = 0; i < nameChar.length; i++)
		{
			try
			{
				//得到转换后的字符数组
				String[] pinyins = PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat);
				
				//转换成功
				if(pinyins != null && pinyins.length > 0)
				{
					pinyinName += pinyins[0] + "_";
				}
				
				//如果不是中文且转换失败
				else
				{
					pinyinName += nameChar[i] + "_";
				}
			}
			catch (BadHanyuPinyinOutputFormatCombination e)
			{
				e.printStackTrace();
			}
		}
		
		//去掉最后一个“_”
		pinyinName = pinyinName.substring(0, pinyinName.length() - 1);
		
		return pinyinName;
	}
}

你可能感兴趣的:(.net)