1

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)

Both lines are 7 characters long however 1 is clearly longer than the other

1Mangomaster1
  • 346
  • 1
  • 6
  • 16
  • 5
    Why not just use a monospace font? – Sumner Evans Jan 19 '21 at 06:47
  • 2
    Show our friend how to set his console to monospace programmatically – Captain Kenpachi Jan 19 '21 at 06:47
  • You could use a table like this one : https://stackoverflow.com/a/56852366/8655660 – Cedervall Jan 19 '21 at 06:49
  • We might need some code to see exactly which Console you are using here... If it's the standard Windows Console ("CMD"), you can't set it programmatically because the police can be set by changing the properties in the console application itself. – Martin Verjans Jan 19 '21 at 06:56
  • Have a look at this question. There are a couple of great examples of creating "tables" in the console. https://stackoverflow.com/questions/856845/how-to-best-way-to-draw-table-in-console-app-c – Captain Kenpachi Jan 19 '21 at 07:09
  • 1
    My main problem is that console is not CMD sadly... It's unity's one I need it for debugging but there is no way to change the font in there. – 1Mangomaster1 Jan 19 '21 at 07:09
  • Related [link](https://forum.unity.com/threads/monospace-console-font.707588/). "As a (terrible) work around if you don't need to click the lines in the console, you can use tail/grep on the editor log. Tail and grep can be added to Windows as well. By default your terminal or command prompt should already be using a monospace font" – John Wu Jan 19 '21 at 07:53

2 Answers2

2

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" );
MD. RAKIB HASAN
  • 3,670
  • 4
  • 22
  • 35
-1

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.

serges_newj
  • 795
  • 1
  • 13
  • 23