Convert Chinese to Unicode and Unicode to Chinese

Source: Internet
Author: User
A problem occurred a few days ago, that is, garbled characters occurred when passing Chinese characters in the address bar of the browser. I considered a lot of solutions. I still used the conversion encoding method, convert Chinese to unicode encoding and then decode it into Chinese. The following is the implementation process, which is very simple!
Package Cy. Code;

Public class cyencoder {
Private string zhstr; // Chinese String
Private string Unicode; // converts a Chinese string to a unicode encoded string and stores it in this attribute.

Public cyencoder (string zhstr ){
This. zhstr = zhstr;
}

Public String getzhstr (){
Return zhstr;
}

Public void setzhstr (string zhstr ){
This. zhstr = zhstr;
}

Public String tounicode (){
Stringbuffer Unicode = new stringbuffer ();
For (INT I = 0; I <zhstr. Length (); I ++ ){
Char c = zhstr. charat (I );
Unicode. append ("\ U" + integer. tohexstring (c ));
}
This. Unicode = Unicode. tostring ();
Return Unicode. tostring ();
}
Public String tozhcn (){
Stringbuffer GBK = new stringbuffer ();
String [] hex = Unicode. Split ("\\\\ U"); // mom, split for half a day !! It is not "\ U", but "\ U"
For (INT I = 1; I <Hex. length; I ++) {// note that it starts from 1, not from 0. The first one is null.
Int DATA = integer. parseint (hex [I], 16); // converts a hexadecimal number to a hexadecimal value.
GBK. append (char) data); // forced conversion to char type is our Chinese character.
}
System. Out. println ("this is a conversion from unicode encoding to Chinese characters:" + GBK. tostring ());
Return GBK. tostring ();
}
Public static void main (string ARGs []) {

Cyencoder fc = new cyencoder ("layout statement ");
System. Out. println (FC. tounicode ());
FC. tozhcn ();
}
} (From: http://w2c2y2.iteye.com/blog/468140)

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.