Compile a function to intercept a string. The input is a string and number of characters, and the output is a string truncated by bytes. However, make sure that the Chinese characters are not cut by half.

Source: Internet
Author: User

Import java. Io. unsupportedencodingexception;
/**
* Question: compile a function to intercept a string. The input is a string and the number of segments. The output is a byte truncation function.
* String. However, make sure that no half of Chinese characters are intercepted, for example, "my ABC" or "4". set it to "my AB" and enter "my ABC ".
* Han Def ", 6, should be output as" I abc "instead of" I ABC + Han half ".
*/
Public class stringtest {
Static void splitstring (string STR, int length)
Throws unsupportedencodingexception {
If (length <= 0 ){
}
Else {
// Decodes the string into a byte sequence according to the encoding format of "GBK" and saves it in the array
// When the Chinese character uses GBK encoding, it occupies two bytes, and when using UTF-8 encoding, it occupies three bytes, and both are negative integers.
Byte [] bt = Str. getbytes ("GBK ");
If (length <= Bt. Length ){
// Determine the number of negative numbers in the array to be truncated.
Int COUNT = 0;
For (INT I = 0; I <length; I ++ ){
If (BT [I] <0)
Count ++;
}
If (count % 2 = 0 ){
// If the code is divisible by 2, no garbled characters will be captured.
System. Out. println (new string (BT, 0, length, "GBK "));
} Else {
// If it cannot be divisible, garbled characters will occur. You need to remove the last byte.
System. Out. println (new string (BT, 0, -- length, "GBK "));
}
}
}

}

Public static void main (string [] ARGs ){
Try {
Stringtest. splitstring ("My ABC Han He Def", 6 );
} Catch (unsupportedencodingexception e ){
E. printstacktrace ();
}
}
}

 

I'm sorry to reference other people's code.

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.