Unicode转中文,中文转Unicode

Unicode中文互转工具类

package util;

/**
 * Unicode中文互转工具类
 * @author 
 * @date 2019年12月28日 下午9:55:32
 */
public class UnicodeUtil {

	public static void main(String[] args) {
		System.out.println(chinaToUnicode("测试"));
		System.out.println(decodeUnicode("干扰\u6d4b\u8bd5\tttt干扰"));
	}

	/**
	 * 把中文转成Unicode码 
	 * @param str
	 * @return
	 * @author 
	 * @date 2019年12月28日 下午9:57:32
	 */
	public static String chinaToUnicode(String str) {
		String result = "";
		int chr1;
		for (int i = 0; i < str.length(); i++) {
			chr1 = (char) str.charAt(i);
			if (chr1 >= 19968 && chr1 <= 171941) {// 汉字范围 \u4e00-\u9fa5 (中文)  
				result += "\\u" + Integer.toHexString(chr1);
			} else {
				result += str.charAt(i);
			}
		}
		return result;
	}

	/**
	 * 判断是否为中文字符
	 * @param c
	 * @return
	 * @author 
	 * @date 2019年12月28日 下午9:57:23
	 */
	public static boolean isChinese(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS 
				|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS 
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A 
				|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION 
				|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION 
				|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
			return true;
		}
		return false;
	}

	/**
	 * Unicode转中文 
	 * @param unicode
	 * @return
	 * @author 
	 * @date 2019年12月28日 下午9:57:13
	 */
	public static String decodeUnicode(final String unicode) {
		StringBuffer string = new StringBuffer();
		String[] hex = unicode.split("\\\\u");
		String chinese, behindString;
		int chr;
		boolean isChinese;
		for (int i = 0; i < hex.length; i++) {
			try {
				// 汉字范围 \u4e00-\u9fa5 (中文)  
				if (hex[i].length() >= 4) {//取前四个,判断是否是汉字  
					chinese = hex[i].substring(0, 4);
					try {
						chr = Integer.parseInt(chinese, 16);
						isChinese = isChinese((char) chr);
						//转化成功,判断是否在  汉字范围内  
						if (isChinese) {//在汉字范围内  
							// 追加成string  
							string.append((char) chr);
							//并且追加  后面的字符  
							behindString = hex[i].substring(4);
							string.append(behindString);
						} else {
							string.append(hex[i]);
						}
					} catch (NumberFormatException e1) {
						string.append(hex[i]);
					}
				} else {
					string.append(hex[i]);
				}
			} catch (NumberFormatException e) {
				string.append(hex[i]);
			}
		}
		return string.toString();
	}
}

 

 

 

 

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值