The output should be "I abc" instead of "I ABC + Han half"

Source: Internet
Author: User
Import java. Io. unsupportedencodingexception;
Public class strspliter {
/**
* Compile a function to intercept a string. The input is a string and the number of characters, and the output is a byte string. However, to ensure that no half of Chinese characters are cut, for example, "my ABC" 4, it should be cut to "my AB ",
* Input "my ABC Han Def", and 6 should be output as "my ABC" instead of "half of my ABC + Han ".
*
* @ Param ARGs
*/
Public static void main (string ARGs []) {
Splitit ("My ABC's def is a Mage", 12 );
}
Public static void splitit (string STR, int bytes ){
Int hanzibytes = 0;
Int interceptbytes = 0;
Byte strbyte [] = NULL;
Try {
Strbyte = Str. getbytes ("GBK"); // the GBK Chinese Character occupies 2 bytes
// Strbyte = Str. getbytes ("UTF-8"); // UTF-8 Chinese characters occupy 3 bytes

} Catch (unsupportedencodingexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
System. Out. println ("untruncated String Length:" + strbyte. Length );
For (INT I = 0; I <bytes; I ++ ){
If (strbyte [I] <0 ){
Hanzibytes ++;
}
}
// When the number of Chinese characters is an even number of bytes, It is intercepted by the total number of bytes. If the number of Chinese characters is an odd number, the total number of bytes is-1.
Interceptbytes = (hanzibytes % 2 = 0 )? Bytes: bytes-1;
/* If (hanzibytes % 3 = 0) {// judgment used by the UTF-8
Interceptbytes = bytes;
} Else if (hanzibytes % 3 = 1 ){
Interceptbytes = bytes-1;
} Else if (hanzibytes % 3 = 2 ){
Interceptbytes = bytes-2;
}*/
Try {
System. Out. println ("screenshot Result:" + new string (strbyte, 0, interceptbytes, "GBK "));
// System. Out. println ("truncated:" + new string (strbyte, 0, interceptbytes, "UTF-8 "));
} Catch (unsupportedencodingexception e ){
E. printstacktrace ();
}
}
}

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.