Search code examples
c#stringformatalignment

How to do Alignment within string.Format in C#?


I have this line of code in C#:

return string.Format("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}", Name, CPSA, PostCode, Rank, Score1, Score2, Score3, Score4, Score5, Score6, Score7, Score8);

It draws its data from a text file and is output in a list box. I want to justify half of it to the left and half to the right so in dream world this:

return string.Format("align=left({0}, {1}, {2}, {3}, {4},) align=right ({5}, {6}, {7}, {8}, {9}, {10}, {11})", Name, CPSA, PostCode, Rank, Score1, Score2, Score3, Score4, Score5, Score6, Score7, Score8);

I have looked around but have no clue how to do it. Can anyone please explain?


Solution

  • You can do something like this:

    Console.WriteLine(String.Format("{0,-10} | {1,5}", "Bill", 51));
    

    You'll get "51" aligned to right on 5 characters.

    More examples here: Align String with Spaces.

    For official reference, see Composite Formatting