.NET Format a string with fixed spaces

user72491 picture user72491 · Mar 13, 2009 · Viewed 248.3k times · Source

Does the .NET String.Format method allow placement of a string at a fixed position within a fixed length string.

"           String Goes Here"
"     String Goes Here      "
"String Goes Here           "

How is this done using .NET?

Edit - I have tried Format/PadLeft/PadRight to death. They do not work. I don't know why. I ended up writing my own function to do this.

Edit - I made a mistake and used a colon instead of a comma in the format specifier. Should be "{0,20}".

Thanks for all of the excellent and correct answers.

Answer

Guffa picture Guffa · Mar 13, 2009

This will give you exactly the strings that you asked for:

string s = "String goes here";
string lineAlignedRight  = String.Format("{0,27}", s);
string lineAlignedCenter = String.Format("{0,-27}",
    String.Format("{0," + ((27 + s.Length) / 2).ToString() +  "}", s));
string lineAlignedLeft   = String.Format("{0,-27}", s);