Java汉字转成汉语拼音工具类,需要用到pinyin4j.jar包.

package zj.pinyin;
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 org.apache.log4j.Logger;
/**
* 汉字转拼音工具类
*
* @version 1.00 (2014.09.15)
* @author SHNKCS 张军 {@link <a target=_blank href=http://www.zhangjunbk.com>张军个人网站</a> <a target=_blank href=http://user.qzone.qq.com/360901061/>张军QQ空间</a>}
*/
public class PinyinUtil {
private transient static final Logger logger = Logger.getLogger(PinyinUtil.class);
/**
* 拼音字母
*
* @param text
* 原字符
* @author 张军
* @date 2016-2-1 9:16:00
* @modifiyNote
* @version 1.0
* @return 拼音首字母
*/
public static String textToPingYin(String text) {
try {
char[] t1 = null;
t1 = text.toCharArray();
String[] t2 = new String[t1.length];
HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
t3.setVCharType(HanyuPinyinVCharType.WITH_V);
int t0 = t1.length;
String t4 = "";
for (int i = 0; i < t0; i++) {
// 判断是否为汉字字符
if (java.lang.Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {
t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);
t4 += t2[0];
} else {
t4 += java.lang.Character.toString(t1[i]);
}
}
return t4;
} catch (Exception e) {
logger.debug("转换拼音出错,返回原字符", e);
return text;
}
}
/**
* 拼音首字母
*
* @param text
* 原字符
* @author 张军
* @date 2016-2-1 9:16:00
* @modifiyNote
* @version 1.0
* @return 拼音首字母
*/
public static String textToPinYinHeadChar(String text) {
try {
String convert = "";
for (int j = 0; j < text.length(); j++) {
char word = text.charAt(j);
String[] pinyinArray = null;
if (java.lang.Character.toString(word).matches("[\\u4E00-\\u9FA5]+")) {
pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word, new HanyuPinyinOutputFormat());
}
if (pinyinArray == null) {
convert += word;
} else {
convert += pinyinArray[0].charAt(0);
}
}
return convert;
} catch (Exception e) {
logger.debug("转换拼音首字母出错,返回原字符", e);
return text;
}
}
/**
* 获取ascii码
*
* @param text
* 原字符
* @author 张军
* @date 2016-2-1 9:16:00
* @modifiyNote
* @version 1.0
* @return ascii码
*/
public static String getCnASCII(String cnStr) {
StringBuffer strBuf = new StringBuffer();
byte[] bGBK = cnStr.getBytes();
for (int i = 0; i < bGBK.length; i++) {
// System.out.println(Integer.toHexString(bGBK[i]&0xff));
strBuf.append(Integer.toHexString(bGBK[i] & 0xff));
}
return strBuf.toString();
}
}
本文为张军原创文章,转载无需和我联系,但请注明来自张军的军军小站,个人博客http://www.zhangjunbk.com

