完美处理unicode码与其他字符串混合的字符串

来源:互联网 发布:宁波院士之乡 知乎 编辑:程序博客网 时间:2024/06/05 03:51

完美处理unicode码与其他字符串混合的字符串

方法一:

[java] view plaincopy
  1. public static String decode(String unicodeStr) {  
  2.     if (unicodeStr == null) {  
  3.         return null;  
  4.     }  
  5.     StringBuffer retBuf = new StringBuffer();  
  6.     int maxLoop = unicodeStr.length();  
  7.     for (int i = 0; i < maxLoop; i++) {  
  8.         if (unicodeStr.charAt(i) == '\\') {  
  9.             if ((i < maxLoop - 5)  
  10.                     && ((unicodeStr.charAt(i + 1) == 'u') || (unicodeStr  
  11.                             .charAt(i + 1) == 'U')))  
  12.                 try {  
  13.                     retBuf.append((char) Integer.parseInt(  
  14.                             unicodeStr.substring(i + 2, i + 6), 16));  
  15.                     i += 5;  
  16.                 } catch (NumberFormatException localNumberFormatException) {  
  17.                     retBuf.append(unicodeStr.charAt(i));  
  18.                 }  
  19.             else  
  20.                 retBuf.append(unicodeStr.charAt(i));  
  21.         } else {  
  22.             retBuf.append(unicodeStr.charAt(i));  
  23.         }  
  24.     }  
  25.     return retBuf.toString();  
  26. }  
方法二:使用org.apache.commons.lang.StringEscapeUtils#unescapeJava(String)方法
原创粉丝点击