java escape unescape

來源:互聯網
上載者:User

public class EscapeUnescape {</p><p>public static String escape(String src) {<br /> int i;<br /> char j;<br /> StringBuffer tmp = new StringBuffer();<br /> tmp.ensureCapacity(src.length() * 6);<br /> for (i = 0; i < src.length(); i++) {<br /> j = src.charAt(i);<br /> if (Character.isDigit(j) || Character.isLowerCase(j)<br /> || Character.isUpperCase(j))<br /> tmp.append(j);<br /> else if (j < 256) {<br /> tmp.append("%");<br /> if (j < 16)<br /> tmp.append("0");<br /> tmp.append(Integer.toString(j, 16));<br /> } else {<br /> tmp.append("%u");<br /> tmp.append(Integer.toString(j, 16));<br /> }<br /> }<br /> return tmp.toString();<br />}</p><p>public static String unescape(String src) {<br /> if(src == null)return null;<br /> StringBuffer tmp = new StringBuffer();<br /> tmp.ensureCapacity(src.length());<br /> int lastPos = 0, pos = 0;<br /> char ch;<br /> while (lastPos < src.length()) {<br /> pos = src.indexOf("%", lastPos);<br /> if (pos == lastPos) {<br /> if (src.charAt(pos + 1) == 'u') {<br /> ch = (char) Integer.parseInt(src<br /> .substring(pos + 2, pos + 6), 16);<br /> tmp.append(ch);<br /> lastPos = pos + 6;<br /> } else if (src.charAt(pos + 1) == ' '<br /> || src.charAt(pos + 1) == ';') {<br /> tmp.append(src.substring(pos, pos + 1));<br /> lastPos = pos + 1;<br /> } else {<br /> ch = (char) Integer.parseInt(src<br /> .substring(pos + 1, pos + 3), 16);<br /> tmp.append(ch);<br /> lastPos = pos + 3;<br /> }<br /> } else {<br /> if (pos == -1) {<br /> tmp.append(src.substring(lastPos));<br /> lastPos = src.length();<br /> } else {<br /> tmp.append(src.substring(lastPos, pos));<br /> lastPos = pos;<br /> }<br /> }<br /> }<br /> return tmp.toString();<br />}</p><p>public static void main(String[] args) {<br /> String tmp = "中文";<br /> System.out.println("testing escape : " + tmp);<br /> tmp = escape(tmp);<br /> System.out.println(tmp);<br /> System.out.println("testing unescape :" + tmp);<br /> System.out.println(unescape("%u6211%u4eec"));<br />}<br />}<br />

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.