Truncate a Chinese string of the specified length in C.

Source: Internet
Author: User
When I write code, I encounter a string with a specified length in the original string. we usually use string. substring (), but this problem is that both Chinese characters and English characters are considered as a point length. because of this, sometimes what we want is not what we want.
I found it online and did not find it. So I wrote one myself. please correct me if there is any error. Thank you!

Private static string SubString (string stringToSub, int length ){
Regex regex = new Regex ("[\ u4e00-\ u9fa5] +", RegexOptions. Compiled );
Char [] stringChar = stringToSub. ToCharArray ();
StringBuilder sb = new StringBuilder ();
Int nLength = 0;

For (int I = 0; I <stringChar. Length; I ++ ){
If (regex. IsMatch (stringChar [I]). ToString ())){
Sb. Append (stringChar [I]);
NLength + = 2;
}
Else {
Sb. Append (stringChar [I]);
NLength = nLength + 1;
}

If (nLength> length)
Break;
}

Return sb. ToString ();
}
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.