Java String字串和Unicode字元相互轉碼__java

來源:互聯網
上載者:User

轉載: http://www.jb51.net/article/56096.htm


這篇文章主要介紹了Java String字串和Unicode字元相互轉碼,需要的朋友可以參考下

java環境安裝後jdk的bin目錄有個native2ascii.exe可以實作類別似的功能,但是通過java代碼也可以實現同樣的功能。

字串轉換unicode java方法程式碼片段:

複製代碼代碼如下:
/**
 * 字串轉換unicode
 */
public static String string2Unicode(String string) {
 
    StringBuffer unicode = new StringBuffer();
 
    for (int i = 0; i < string.length(); i++) {
 
        // 取出每一個字元
        char c = string.charAt(i);
 
        // 轉換為unicode
        unicode.append(" \\u" + Integer.toHexString(c));
    }
 
    return unicode.toString();
}

unicode轉換字串java方法程式碼片段:

複製代碼代碼如下:
/**
 * unicode 轉字串
 */
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();
}

測試java程式碼片段:

複製代碼代碼如下:
public static void main(String[] args) {
    String test = "最代碼網站地址:www.zuidaima.com";
 
    String unicode = string2Unicode(test);
     
    String string = unicode2String(unicode) ;
     
    System.out.println(unicode);
     
    System.out.println(string);
 
}

輸出結果:

\u6700\u4ee3\u7801\u7f51\u7ad9\u5730\u5740\u3a\u77\u77\u77\u2e\u7a\u75\u69\u64\u61\u69\u6d\u61\u2e\u63\u6f\u6d

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.