I am trying to print some information in a column-oriented way. Everything works well for Latin characters, but when Chinese characters are printed, the columns stop being aligned. Let's consider an example:
var latinPresentation1 = "some text".PadRight(30) + "| " + 23;
var latinPresentation2 = "some longer text".PadRight(30) + "| " + 23;
Console.WriteLine(latinPresentation1);
Console.WriteLine(latinPresentation2);
Console.WriteLine("..............................................");
var chinesePresentation1 = "一些文字".PadRight(30) + " | " + 23;
var chinesePresentation2 = "一些較長的文字".PadRight(30) + "| " + 23;
Console.WriteLine(chinesePresentation1);
Console.WriteLine(chinesePresentation2);
Output:
some text | 23
some longer text | 23
.................................................
一些文字 | 23
一些較長的文字 | 23
As one can see, the Chinese is not aligned to columns. Important note: this is just a presentation of the problem; it won't be used in a console app. Can anyone help me with this?
English and the other Latin languages use ASCII encoding; Simplified Chinese uses GB2312 encoding, Traditional Chinese uses Big 5 encoding, and so forth. In other words, a computer using Big 5 encoding cannot read computer code in GB2312 or ASCII encoding.
Unicode/UTF-8 characters include: Chinese characters. any non-Latin scripts (Hebrew, Cyrillic, Japanese, etc.) symbols.
Set the language that defines default behavior in Microsoft Office applications to "Chinese (Simplified)". This option is located on Start > Programs > Microsoft Office > Microsoft Office Tools > Microsoft Office Language Settings > Enabled Languages.
You can use the TextRenderer.MeasureText method from System.Windows.Forms assembly to build the output text basing on string width, instead of characters count.
Here's the util method:
public static string FillWithSpaces(this string text, int width, Font font)
{
while (TextRenderer.MeasureText(text, font).Width < width)
{
text += ' ';
}
return text;
}
And the usage:
var font = new Font("Courier New", 10.0F);
var padding = 340;
var latinPresentation1 = "some text ".FillWithSpaces(padding, font) + "| 23";
var latinPresentation2 = "some longer text".FillWithSpaces(padding, font) + "| 23";
var chinesePresentation1 = "一些文字".FillWithSpaces(padding, font) + "| 23";
var chinesePresentation2 = "一些較長的文字".FillWithSpaces(padding, font) + "| 23";
var result = latinPresentation1 + Environment.NewLine +
latinPresentation2 + Environment.NewLine +
".............................................." + Environment.NewLine +
chinesePresentation1 + Environment.NewLine +
chinesePresentation2;
The solution requires padding parameter (in px) and font used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With