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 *******";