Extension string left-right Alignment Method

Source: Internet
Author: User

The string. padright method that comes with. NET is described in msdn as follows:
Align the characters in this string to the left, and fill the string with spaces or specified Unicode characters on the right to reach the specified total length.
Problems found during actual use: it is inevitable for Chinese users to simultaneously process double-byte Chinese characters and single-byte characters, at this time, this method cannot achieve the so-called alignment effect;
To this end, we have the following function. After processing this function, we can correctly obtain strings of the same placeholder length regardless of whether the string contains a Chinese/English mixed rank.
Private string padrightex (string STR, int totalbytecount)
{
Encoding coding = encoding. getencoding ("gb2312 ");
Int dcount = 0;
Foreach (char CH in Str. tochararray ())
{
If (coding. getbytecount (ch. tostring () = 2)
Dcount ++;
}
String W = Str. padright (totalbytecount-dcount );
Return W;
}

This function uses the default space filling format. You can also add any required characters:
Private string padrightex (string STR, int totalbytecount, char ch)
{
...
String W = Str. padright (totalbytecount-dcount, CH );
...
}
String. padleft can also be expanded according to this extension.
For example:
Console. Write (padrightex ("medium.", 12, '*') + "\ r \ n ");
Console. Write (padrightex ("Chinese E", 12, '*') + "\ r \ n ");

Output:
"In .*********";
"Chinese e *******";

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.