pinyin4j 是一个流行的Java库,支持将中文字符转换为拼音,拼音输出格式可以自己设置,本篇我们就介绍如何将汉字转换成拼音。
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;
/**
*
* @author Admin
*
*/
public class JavaUtils{
/**
* 输入字符串,将字符串中的汉字转换成拼音,其余不变
* @param pinYinStr
* @return
*/
public static String getStringPinYin(String pinYinStr){
//定义pinyin4j格式类
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
//设置转换格式为只讲汉字转换成拼音,不需要声调HanyuPinyinToneType.
//HanyuPinyinCaseType里面有两个常量
//LOWERCASE输出为小写
//UPPERCASE输出为大写
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
//HanyuPinyinToneType里面有三个变量
//WITH_TONE_MARK 吕不韦:lǚbùwéi 意我们标准拼音形式显示
//WITH_TONE_NUMBER 吕不韦:lu:3bu4wei2 用数字的形式显示音调
//WITHOUT_TONE 吕不韦:lu:buwei 不显示音调
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
//WITH_U_UNICODE 显示ü
//WITH_V 显示V
//WITH_U_AND_COLON 显示u:
format.setVCharType(HanyuPinyinVCharType.WITH_V);
String[] pinyin = null;
StringBuffer sb = new StringBuffer();
String tempStr = null;
//循环传入的字符串
for(int i = 0; i<pinYinStr.length(); i++)
{
try
{
//转换字符串中每一个字符
pinyin = PinyinHelper.toHanyuPinyinStringArray(pinYinStr.charAt(i), format);
} catch (BadHanyuPinyinOutputFormatCombination e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//如果为非汉字设置为null
if(pinyin == null){
tempStr = null;
}else{
//多音字会返回一个多音字拼音的数组,我们取第一个
tempStr = pinyin[0];
}
if(tempStr == null)
{
//非汉字直接拼接
sb.append(pinYinStr.charAt(i));
}else
{
sb.append(tempStr);
}
}
return sb.toString();
}
}
这样一个简单的汉语转拼音的功能就实现了。
//测试数据:
String str = "你在做什么? What are you doing?";
System.out.println(getStringPinYin(str));
//数据结果:
nizaizuoshenme? What are you doing?