C # Calculate Chinese characters as 2 Characters

Source: Internet
Author: User

In the current project, you need to calculate the length of the string and cut down the Fixed Length characters. The Chinese character must be calculated as two characters, and the numbers and letters must be calculated as one character, no ready-made functions found can be used, refer to how to get an exact length of a Chinese character and letter combination string (Asp.net version) http://www.webjx.com/htmldata/2005-10-20/1129777793.html

I have written the following two functions for reference. The main function is to take the copy String Based on the specified length and replace the substring function.

Private int getlength (string aorgstr)
{
Int intlen = aorgstr. length;
Int I;
Char [] chars = aorgstr. tochararray ();
For (I = 0; I <chars. length; I ++)
{
If (system. Convert. toint32 (chars [I])> 255)
{
Intlen ++;
}
}
Return intlen;
}

Private string mutisubstring (string aorgstr, int alength, ref string aafterstr)
{
Int intlen = aorgstr. length;
Int start = 0;
Int end = intlen;
Int single = 0;
Char [] chars = aorgstr. tochararray ();
For (INT I = 0; I <chars. length; I ++)
{
If (system. Convert. toint32 (chars [I])> 255)
{
Start + = 2;
}
Else
{
Start + = 1;
Single ++;
}
If (Start> = alength)
{

If (end % 2 = 0)
{
If (single % 2 = 0)
{
End = I + 1;
}
Else
{
End = I;
}
}
Else
{
End = I + 1;
}
Break;
}
}
String temp = aorgstr. substring (0, end );
String temp2 = aorgstr. Remove (0, end );
Aafterstr = temp2;
Return temp;
}

Running result:

STR = mutisubstring ("ABC Chinese character", 5, aafterstr)

STR = "ABC Han"

Aafterstr = "character"

The problem of using Str. length as a character

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.