How to do Alignment within string.Format c#?

2020-01-29 07:28发布

Hi I have a problem I have this line of code:

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 it 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, i am also a bit of a codeing noob so please explain. code is C# Thanks

1条回答
Animai°情兽
2楼-- · 2020-01-29 08:05

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, look Composite Formatting

查看更多
登录 后发表回答