44

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?

3
  • A listbox has its own idea how to align text, string.Format() doesn't count. Your question is unanswerable until you document what kind of ListBox class you use. Commented Jan 2, 2011 at 17:31
  • Aligned left in concern to what? Where is the text going to printed? HTML, Silverlight, console or Winforms Commented Jan 2, 2011 at 17:32
  • In general each character has a different width so aligning with spaces won't work unless you're forcing the listbox to use a monospaced font... you'd need to tabulate the data and for that we'd need a better example on what you're trying to achieve. Commented Jan 2, 2011 at 17:50

2 Answers 2

86

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

Sign up to request clarification or add additional context in comments.

2 Comments

csharp-examples.net/align-string-with-spaces resolves to a poker site on my PC
@DanMarshall, you can always use the Wayback Machine, especially for old posts like this one
5

Additionally, to use alignment with C#6 string interpolation + formatting, for a quick reference, write it like this:

float avg = 3.48f;
float peak = 5.00f;
$"in : {avg,5:F1} K/s | peak {peak,5:F1} K"

const int Indent = 5; // In which indent part can also refer variable
$"in : {avg,Indent:F1} K/s | peak {peak,Indent:F1} K"

Will yield

"in :   3.5 K/s | peak   5.0 K"

See https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.