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.