.NET Format a string with fixed spaces
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.
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);
As of Visual Studio 2015 you can also do this with Interpolated Strings (its a compiler trick, so it doesn't matter which version of the .net framework you target).
string value = "String goes here";
string txt1 = $"{value,20}";
string txt2 = $"{value,-20}";
The first and the last, at least, are possible using the following syntax:
String.Format("{0,20}", "String goes here");
String.Format("{0,-20}", "String goes here");