汉语转拼音pinyin4j

时间:2024-01-19 16:30:20

分享一个将汉语转成拼音的工具包:pinyin4j-2.5.0.jar,下载地址:http://download.csdn.net/detail/abc_key/7629141

使用例如以下代码

import net.sourceforge.pinyin4j.PinyinHelper;

public class HanyuToPinyin {

	/*
* 讲汉语转成拼音
*/
public static String ToHanyuPinyin(String sourceStr, boolean isUpperCase) {
int sourceLen = sourceStr == null ? 0 : sourceStr.length();
if (sourceLen < 1)
return "";
StringBuffer pinyinStrBuf = new StringBuffer();
for (int idx = 0; idx < sourceLen; idx++) {
String[] tmpData = PinyinHelper.toHanyuPinyinStringArray(sourceStr
.charAt(idx));
if (tmpData != null && tmpData.length > 0
&& tmpData[0].length() > 0) {
if (isUpperCase) {
pinyinStrBuf.append(tmpData[0].substring(0,
tmpData[0].length() - 1).toUpperCase());
} else {
pinyinStrBuf.append(tmpData[0].substring(0, tmpData[0]
.length() - 1));
}
}
}
return pinyinStrBuf.toString();
} /*
* 汉语转成拼音的首字母
*/
public static String ToHanyuPinyinHead(String sourceStr, boolean isUpperCase) {
int sourceLen = sourceStr == null ? 0 : sourceStr.length();
if (sourceLen < 1)
return "";
StringBuffer pinyinStrBuf = new StringBuffer();
for (int idx = 0; idx < sourceLen; idx++) {
String[] tmpData = PinyinHelper.toHanyuPinyinStringArray(sourceStr
.charAt(idx));
if (tmpData != null && tmpData.length > 0
&& tmpData[0].length() > 0) {
if (isUpperCase) {
pinyinStrBuf.append(tmpData[0].substring(0,
1).toUpperCase());
} else {
pinyinStrBuf.append(tmpData[0].substring(0, 1));
}
}
//物品名称中不能转换成拼音的部分(英数)会原样保存
else{
pinyinStrBuf.append(sourceStr.charAt(idx));
}
}
return pinyinStrBuf.toString();
}
}