Requirements:
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 no half of Chinese characters are cut, for example, "my ABC" 4, it should be cut to "my AB", input "my ABC Han DEF", 6, the output should be "I abc" instead of "I ABC + Han ".
Basic knowledge:
First, let's take a look at the basic units:
1. bit is a binary bit. For example, 100011 is 6 bits.
2. bytes (byte), which is the most basic unit of data type in the computer. 8 bits constitute 1 byte.
Java needs to determine the size of the storage space occupied by each basic type. Their size does not change as the Random Device hardware architecture changes in most other languages. This immutability of the size of storage space is one of the reasons why java programs have the ability to shift values.
In java, the boolean length is 1 byte. In fact, it only takes 1 bit to work, and all others are 0.
The size of basic data in java is as follows:
Boolean 1-byte (in fact, 1bit is working)
Char 2-bytes
Byte 1-byte
Short 2-bytes
Int 4-bytes
Long 8-bytes
Float 4-bytes
Double 8-bytes
A letter or a Chinese character is a Unicode code unit, Unicode is currently widely used in UCS-2, it uses two bytes to encode a character, A character is a code unit in Unicode.
Code Public String splitString (String src, int size ){
String result = new String (src. getBytes (), 0, size );
If (! Src. startsWith (result )){
Result = new String (src. getBytes (), 0, size-1 );
}
Return result;
}
Note that if you use Eclipse to write a test program, set the text encoding to GBK. Otherwise, the results may be different.