汉字转换成拼音

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;
public class ChineseConvert {
	private static final HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
	static {
		defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
                // 遇到“ü” 显示成V
		defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
                // 所有输出大写
		defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
	}
	
	/**
	 * 中文字符串转拼音全写.
	 * 
	 * @param resource - 中文字符串
	 * @return - 拼音全写
	 */
	public static String convertFull(String resource) {
		return convert(resource, true);
	}
	
	/**
	 * 中文字符串转拼音缩写,取汉字拼音的第一个字母.
	 * 
	 * @param resource - 中文字符串
	 * @return - 拼音全写
	 */
	public static String convertFirstWord(String resource) {
		return convert(resource, false);
	}
	
	/**
	 * 中文字符串转拼音.
	 * 
	 * @param resource - 中文字符串
	 * @param isFull - 是否全写. true - 全写, false - 缩写
	 * @return - 拼音字符串
	 */
	public static String convert(String resource, boolean isFull) {
		StringBuffer buff = new StringBuffer(0);
		try {
			char temp;
			String[] convertArray = null;
			char[] pinyinArray = resource.toCharArray();
			for (int i = 0, j = pinyinArray.length; i < j; i++) {
				temp = pinyinArray[i];
				if (128 < temp) {
					convertArray = PinyinHelper.toHanyuPinyinStringArray(temp, defaultFormat);
					if (null != convertArray && convertArray.length > 0) {
						if (isFull)
							buff.append(convertArray[0]);
						else
							buff.append(convertArray[0].charAt(0));
					}
				} else {
					buff.append(temp);
				}
			}
		} catch (BadHanyuPinyinOutputFormatCombination e) {
			e.printStackTrace();
		}
		return buff.toString().replaceAll("\\W", "").trim();
	}
}
所需jar包: pinyin4j.jar

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值