栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java实现中文字符串与unicode互转工具类

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java实现中文字符串与unicode互转工具类

本文实例为大家分享了Java实现中文字符串与unicode互转的具体代码,供大家参考,具体内容如下

原理利用了java实现js的escape以及unescape函数。


public class UnicodeConvertUtils {

  
  public static String escape(String input) {
    int len = input.length();
    int i;
    char j;
    StringBuffer result = new StringBuffer();
    result.ensureCapacity(len * 6);
    for (i = 0; i < len; i++) {
      j = input.charAt(i);
      if (Character.isDigit(j) || Character.isLowerCase(j) || Character.isUpperCase(j)) {
 result.append(j);
      } else if (j < 256) {
 result.append("%");
 if (j < 16) {
   result.append("0");
 }
 result.append(Integer.toString(j, 16));
      } else {
 result.append("%u");
 result.append(Integer.toString(j, 16));
      }
    }
    return result.toString();

  }

  
  public static String unescape(String input) {
    int len = input.length();
    StringBuffer result = new StringBuffer();
    result.ensureCapacity(len);
    int lastPos = 0, pos = 0;
    char ch;
    while (lastPos < len) {
      pos = input.indexOf("%", lastPos);
      if (pos == lastPos) {
 if (input.charAt(pos + 1) == 'u') {
   ch = (char) Integer.parseInt(input.substring(pos + 2, pos + 6), 16);
   result.append(ch);
   lastPos = pos + 6;
 } else {
   ch = (char) Integer.parseInt(input.substring(pos + 1, pos + 3), 16);
   result.append(ch);
   lastPos = pos + 3;
 }
      } else {
 if (pos == -1) {
   result.append(input.substring(lastPos));
   lastPos = len;
 } else {
   result.append(input.substring(lastPos, pos));
   lastPos = pos;
 }
      }
    }
    return result.toString();
  }

  
  public static String toGb2312(String input) {
    input = input.trim().replaceAll("(?i)\\u", "%u");
    return unescape(input);
  }

  
  public static String toUnicode(String input) {
    input = input.trim();
    String output = escape(input).toLowerCase().replace("%u", "\u");
    return output.replaceAll("(?i)%7b", "{").replaceAll("(?i)%7d", "}").replaceAll("(?i)%3a", ":")
 .replaceAll("(?i)%2c", ",").replaceAll("(?i)%27", "'").replaceAll("(?i)%22", """)
 .replaceAll("(?i)%5b", "[").replaceAll("(?i)%5d", "]").replaceAll("(?i)%3D", "=")
 .replaceAll("(?i)%20", " ").replaceAll("(?i)%3E", ">").replaceAll("(?i)%3C", "<")
 .replaceAll("(?i)%3F", "?").replaceAll("(?i)%5c", "\");
  }

  
  public static void main(String[] args) {
    System.out.println(toUnicode("你好"));
    System.out.println(toGb2312("u4f60u597d"));
    // 等同于上面
    System.out.println(toGb2312("\u4f60\u597d"));
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/138373.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号