Java string strings and Unicode characters convert code to each other _java

Source: Internet
Author: User
Tags stringbuffer

After the Java environment is installed, the JDK's Bin directory has a native2ascii.exe that can achieve similar functions, but it can also achieve the same functionality through Java code.

String Conversion Unicode Java method code fragment:

Copy Code code as follows:

/**
* String Conversion Unicode
*/
public static string String2unicode (String string) {

StringBuffer Unicode = new StringBuffer ();

for (int i = 0; i < string.length (); i++) {

Remove each character
char C = String.charat (i);

Convert to Unicode
Unicode.append ("\\u" + integer.tohexstring (c));
}

return unicode.tostring ();
}

Unicode conversion string Java method code fragment:

Copy Code code as follows:

/**
* Unicode Spin string
*/
public static string Unicode2string (string Unicode) {

StringBuffer string = new StringBuffer ();

string[] hex = Unicode.split (" \\\\u");

for (int i = 1; i < hex.length; i++) {

Convert every code point
int data = Integer.parseint (Hex[i], 16);

Append As String
String.append ((char) data);
}

return string.tostring ();
}

Test Java Code Snippets:

Copy code code as follows:

public static void Main (string[] args) {
    String test = "Most code Web site address: Www.zuidaim A.com ";
 
    String Unicode = string2unicode (test);
    
    String string = Unicode2string (Unicode);
    
    System.out.println (Unicode);
    
    System.out.println (string);
 
}

Output:

\u6700\u4ee3\u7801\u7f51\u7ad9\u5730\u5740\u3a\u77\u77\u77\u2e \U7A\U75\U69\U64\U61\U69\U6D\U61\U2E\U63\U6F\U6D

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.