Java String字符串和Unicode字符相互转换代码(包括混有普通字符的Unicode)

unicode转换字符串java方法代码片段:

/**

* unicode 转字符串

* @param unicode 全为 Unicode 的字符串

* @return

*/

public static String unicode2String(String unicode) {

StringBuffer string = new StringBuffer();

String[] hex = unicode.split("\\\\u");

for (int i = 1; i < hex.length; i++) {

// 转换出每一个代码点

int data = Integer.parseInt(hex[i], 16);

// 追加成string

string.append((char) data);

}

return string.toString();

}

结合正则实现的代码:

混有普通字符的Unicode转换为字符串:

/**

* 含有unicode 的字符串转一般字符串

* @param unicodeStr 混有 Unicode 的字符串

* @return

*/

public static String unicodeStr2String(String unicodeStr) {

int length = unicodeStr.length();

int count = 0;

//正则匹配条件,可匹配“\\u”1到4位,一般是4位可直接使用 String regex = "\\\\u[a-f0-9A-F]{4}";

String regex = "\\\\u[a-f0-9A-F]{1,4}";

Pattern pattern = Pattern.compile(regex);

Matcher matcher = pattern.matcher(unicodeStr);

StringBuffer sb = new StringBuffer();

while(matcher.find()) {

String oldChar = matcher.group();//原本的Unicode字符

String newChar = unicode2String(oldChar);//转换为普通字符

// int index = unicodeStr.indexOf(oldChar);

// 在遇见重复出现的unicode代码的时候会造成从源字符串获取非unicode编码字符的时候截取索引越界等

int index = matcher.start();

sb.append(unicodeStr.substring(count, index));//添加前面不是unicode的字符

sb.append(newChar);//添加转换后的字符

count = index+oldChar.length();//统计下标移动的位置

}

sb.append(unicodeStr.substring(count, length));//添加末尾不是Unicode的字符

return sb.toString();

}

public static void main(String[] args) {

String str = "abc";

String str2 = string2Unicode(str);

System.out.println(str2);

System.out.println(unicodeStr2String(str2));

System.out.println(unicodeStr2String("\\u61HJ\\u62\\u63(sfkfdsl)"));

}

————————————————

(120条消息) Java String字符串和Unicode字符相互转换代码(包括混有普通字符的Unicode)_string 转unioncode编码_JodenHe的博客-优快云博客

中点(·)在UTF-8和GBK转换中的问题 · Dark Side (0x08.org)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值