Problem scenario: In a string, an English character occupies one byte, while a Chinese character occupies two bytes. The number of bytes is used to intercept a string. Therefore, the preceding problem occurs.
It is possible to extract half Chinese characters.
Solution: If the placeholder bytes of English characters and Chinese characters are the same in the string, then this problem will not occur. Can we find a conversion method? So that the number of occupied bytes in English is the same as the number of occupied bytes in Chinese characters, the problem can be well solved, in fact, when we first started learning Java, we realized that the char type character in Java occupies two bytes. The problem has been solved.
Algorithm:
Input: String, truncation length;
1. convert a string to an array of the char type (Key conversion)
2. Take the equal-length characters in the array
3. Construct new string and return
Sample Code and test:
-
Java code
-
Public class outerclass {public static string cutstring (string STR, int length) {char [] B = Str. tochararray (); // converts a string to a char-type array string S = new string (B, 0, length); // return s, an equal-length character in the array ;} public static void main (string [] ARGs) {system. out. println (cutstring ("Wo is a good person ABC", 5 ));}}
Output: Wo is a good person.
Another implementation method:
-
Java code
-
Public class outerclass {public static string cutstring (string STR, int begin, int end) {char [] B = Str. tochararray (); string S = new string (B, begin, end-begin); // note [color = # ff0000] End-begin [/color] Return s ;} public static void main (string [] ARGs) {system. out. println (cutstring ("Wo is a good person ABC ));}}
Output: good guy