C # How to obtain a mix of Chinese and English strings with a specified byte length

Source: Internet
Author: User

During database insertion, if you use the insert statement to insert content to a varchar field, an error is reported because the length of the inserted content exceeds the specified length. In particular, when inserting a mix of Chinese and English strings, SQL Server generally occupies two bytes of Chinese characters. Therefore, a mixed string must be processed, and the length of the string is calculated in bytes. The method is as follows:
/// <Summary>
/// Obtain a mix of Chinese and English strings with a specified byte length
/// </Summary>
Private string getstring (string STR, int Len)
{
String result = string. Empty; // The final returned result.
Int bytelen = system. Text. encoding. Default. getbytecount (STR); // length of a single byte
Int charlen = Str. length; // String Length when the characters are treated equally
Int bytecount = 0; // record the read progress
Int Pos = 0; // record position
If (bytelen> Len)
{
For (INT I = 0; I <charlen; I ++)
{
If (convert. toint32 (Str. tochararray () [I])> 255) // calculate by Chinese Character and add 2
Bytecount + = 2;
Else // Add 1 to the English character
Bytecount + = 1;
If (bytecount> Len) // when the value exceeds the upper limit, only the previous valid position is recorded.
{
Pos = I;
Break;
}
Else if (bytecount = Len) // write down the current location
{
Pos = I + 1;
Break;
}
}

If (Pos> = 0)
Result = Str. substring (0, POS );
}
Else
Result = STR;

Return result;
}

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.