Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 955
HadlowJ Avatar asked Jan 02 '11 17:01

HadlowJ


People also ask

How do you right align a string in C?

By using justifications in printf statement we can arrange the data in any format. To implement the right justification, insert a minus sign before the width value in the %s character.

How do I center a string format?

You can now use StringUtils. center(String s, int size) in String. format .

What does %* s mean in C?

*s means you are reading the precision value from an argument, and precision is the maximum number of characters to be printed, and %*s you are reading the width value from an argument, which is the minimum number os characters to be printed. – Vargas. Sep 24, 2021 at 20:50.

How do I center a string in C#?

double theObject = Math. PI; string test = string. Format("Now '{0:F4}' is used.", theObject. Center(10));


1 Answers

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

like image 154
Rubens Farias Avatar answered Sep 28 '22 14:09

Rubens Farias