Chinese and English string truncation method

Source: Internet
Author: User

Public static string Intercept (string input, int p) {Encoding encode = Encoding. getEncoding ("gb2312"); byte [] byteArr = encode. getBytes (input); if (byteArr. length <= p) return input;
Int m = 0, n = 0; foreach (byte B in byteArr) {if (n> = p) break; if (B> 127) m ++; // important step: Count the characters whose values in the first p bytes are greater than 127 plus n ++;} if (m % 2! = 0) n = p + 1; // if it is not even: It indicates that the end is a double byte character, the number of truncated digits plus 1
Return encode. GetString (byteArr, 0, n );}
Console. writeLine (Intercept ("ABC Chinese", 7); Console. writeLine (Intercept ("ABCD Chinese", 7); Console. writeLine (Intercept ("ABC Chinese D", 7 ));
Test code result:
ABC China ABCD China ABC China D

Related Article

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.