Pankaj Pankaj - 7 months ago 48
C# Question

Aligning string with spaces

Is there a way to perfectly align two strings in C#?
I am trying to align the string "CBI" with "Central Bureau of Investigation" and I want both strings to occupy 35 characters. I use the function

string.Format("{0,-35}", str);

to format both strings. But they do not appear to be aligned properly. Does it have something to do with the font settings?
I have to use these strings in a chart in excel and they have to occupy the same width on the screen


Yes there is PadLeft and PadRight


str = "BBQ and Slaw";
Console.WriteLine(str.PadLeft(15));  // Displays "   BBQ and Slaw".
Console.Write(str.PadRight(15));     // Displays "BBQ and Slaw   ".

Side Note from documentation:

However, if totalWidth is less than the length of this instance, the method returns a reference to the existing instance

Basically if your length is less than the length of the string then an reference of the existing string is returned

If EvenMcDonnal wishes to include this in an answer I'll gladly remove it from my answer.

You can find a list of MonoSpaced fonts you can use here