String Truncation in Java to avoid simple implementation of intercepting half Chinese Characters

Source: Internet
Author: User
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

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.