C # specify the length of a Chinese/English string

Source: Internet
Author: User

// Whether the character is a Chinese character
Public bool IsChinese (char c)
{
Return (int) c >=0x4e00 & (int) c <= 0x9FA5;
}
// Get the byte length
Private int getLengthb (string str)
{
Return System. Text. Encoding. Default. GetByteCount (str );
}

// C # specifies the length of the string, startidx from 0 by gisoracle@126.com
Public string getStrLenB (string str, int startidx, int len)
{
Int Lengthb = getLengthb (str );
If (startidx + 1> Lengthb)
{
Return "";
}
Int j = 0;
Int l = 0;
Int strw = 0; // character width
Bool B = false;
String rstr = "";
For (int I = 0; I <str. Length; I ++)
{
Char c = str [I];
If (j> = startidx)
{
Rstr = rstr + c;
B = true;
}
If (IsChinese (c ))
{
Strw = 2;
}
Else
{
Strw = 1;
}
J = j + strw;
If (B)
{
L = l + strw;
If (l + 1)> = len) break;

}


}
Return rstr;

 

}

Private void button4_Click (object sender, EventArgs e) // test by yl gisoracle@126.com
{
MessageBox. Show (getStrLenB ("gisoracle welcomes you gisoracle", 0, 10); // gisoracle
MessageBox. Show (getStrLenB ("gisoracle welcome gisoracle", 1, 10); // isoracle Huan
MessageBox. Show (getStrLenB ("gisoracle welcomes you gisoracle", 2, 10); // isoracle Huan
}

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.