Chinese characters in C # are calculated as 2 characters

Source: Internet
Author: User

In the current project, the length of the string is computed and the fixed-length character is truncated, in which the Chinese character is calculated in 2 characters, the number and the letter are calculated in 1 characters, and no ready-made functions can be used to refer to how to get the exact length of a string of characters and letters (asp.net version) Http://www.webjx.com/htmldata/2005-10-20/1129777793.html

The reference is written with the following two functions, the main function of which is to take the copy string at a specified length instead of sub

The function of string.

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.sub
String (0, end);
  
String temp2 = Aorgstr.remove (0,end);
Aafterstr = Temp2;
return temp;
}
Run Result:

str = MutiSubString( "abc汉字字符", 5 , aAfterStr )
str = "abc汉"
aAfterStr ="字字符"

has been and has been using STR for a long time. Length the problem of using Chinese characters 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.