简体   繁体   中英

C# Console table is not aligned

I managed to make a simple C# table in a console, there are more than enough threads regarding that. The problem is due to characters having different sizes(for example 'iiiii'(5 chars) is shorter than 'there'(5 chars)) The table will never be aligned.

Is there a way to calculate the real length of the string value in order to tell how many more spaces need to be added to align the shorter string with the rest of the table?

(I tried to visually display it here but it seems that in the font this site is using all characters have an equal size(and/or padding), However, I can send a screenshot)

两行都是 7 个字符长,但 1 显然比另一行长

Instead of trying to manually align the text into columns with arbitrary strings of spaces, you should embed actual tabs (the \t escape sequence) into each output string.

Console.WriteLine("Row1:" + "\t"
    + "iiiiiii" );
Console.WriteLine("Row2:" + "\t"
    + "7 chars" );

If you know console font name and size, you can try to use TextRenderer.MeasureText to get strings widths in pixels. Then add spaces to shorter ones until strings will be aligned.

Of course you will not get precise positioning this way, but probably it will suit your needs.

UPD . You can refer to How to measure the pixel width of a digit in a given font / size (C#) and/or other similar questions for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM