public String decodeUnicode(String src) { char[] in = src.toCharArray(); char aChar; char[] out = new char[src.length()]; int outLen = 0; int off = 0; int end = src.length();
while (off < end) { aChar = in[off++]; if (aChar == ‘\\‘) { aChar = in[off++]; if (aChar == ‘u‘) { int value = 0; for (int i = 0; i < 4; i++) { aChar = in[off++]; switch (aChar) { case ‘0‘: case ‘1‘: case ‘2‘: case ‘3‘: case ‘4‘: case ‘5‘: case ‘6‘: case ‘7‘: case ‘8‘: case ‘9‘: value = (value << 4) + aChar - ‘0‘; break; case ‘a‘: case ‘b‘: case ‘c‘: case ‘d‘: case ‘e‘: case ‘f‘: value = (value << 4) + 10 + aChar - ‘a‘; break; case ‘A‘: case ‘B‘: case ‘C‘: case ‘D‘: case ‘E‘: case ‘F‘: value = (value << 4) + 10 + aChar - ‘A‘; break; default: throw new IllegalArgumentException( "Malformed \\uxxxx encoding."); } } out[outLen++] = (char) value; } else { if (aChar == ‘t‘) { aChar = ‘\t‘; } else if (aChar == ‘r‘) { aChar = ‘\r‘; } else if (aChar == ‘n‘) { aChar = ‘\n‘; } else if (aChar == ‘f‘) { aChar = ‘\f‘; } out[outLen++] = aChar; } } else { out[outLen++] = (char) aChar; } } return new String(out, 0, outLen); }
|
public String encodeUnicode(String str) { int iValue = 0; String uStr = ""; for (int i = 0; i < str.length(); i++) { iValue = (int) str.charAt(i); if (iValue <= 256) { uStr += str.charAt(i); } else { uStr += "\\u" + Integer.toHexString(iValue); } } return uStr; } |
public String encoding(String srcStr){
String desStr = ""; try { desStr = URLEncoder.encode(srcStr, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }
return desStr; } |
public String decoding(String srcStr){ String desStr = "";
try { desStr = URLDecoder.decode(srcStr, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return desStr; } |
原文:http://blog.csdn.net/u022812849/article/details/43798751