How to Align Text in Columns Using Console.Writeline

How can I align text in columns using Console.WriteLine?

Instead of trying to manually align the text into columns with arbitrary strings of spaces, you should embed actual tabs (the \t escape sequence) into each output string:

Console.WriteLine("Customer name" + "\t"
+ "sales" + "\t"
+ "fee to be paid" + "\t"
+ "70% value" + "\t"
+ "30% value");
for (int DisplayPos = 0; DisplayPos < LineNum; DisplayPos++)
{
seventy_percent_value = ((fee_payable[DisplayPos] / 10.0) * 7);
thirty_percent_value = ((fee_payable[DisplayPos] / 10.0) * 3);
Console.WriteLine(customer[DisplayPos] + "\t"
+ sales_figures[DisplayPos] + "\t"
+ fee_payable + "\t\t"
+ seventy_percent_value + "\t\t"
+ thirty_percent_value);
}

Trying to align what is output to the console

You could use string formatting with alignment to create columns of characters. This is feasible when your output console uses a fixed width font.

For example your first line could be written as

Console.WriteLine("{0,-40}{1,-50}", "Employee Name:", empName);

This will write "Employee Name;" in a column of 40 characters aligned on the left side and filling the remainder with spaces to reach the 40 characters width. Then a new column with a 50 chars width will receive the value of empname aligned on the left of the colum

The line with the Income tax rate could be written as

Console.WriteLine("{0,-30}{1,10:F2}%{2,50:F2}", 
"Income Tax:", INCOME_TAX_RATE, incomeTaxPayable);

this will reduce the first column to just 30 chars for the label and add a column with 10 character that will be filled with the value of INCOME_TAX_RATE aligned on the right. Of course this could be repeated for the other lines

This is well explained in the MSDN article called Composite Formatting

C# Align Text Right in Console

I would suggest using curses as @Oded said.

If you really don't want to use any third party libraries, you can use Console.BufferWidth to get size of console and then Console.Console.CursorLeft to set column position.

Console.CursorLeft = Console.BufferWidth - 4;
Console.Write("[ok]");

The above prints [ok] at the end of the current line, leaving cursor at the first column, next line

C# Console columns formatting and positioning

Why is there is a space before the first asdf?

Because the ,5 in {0,5} means "align to 5 characters", and "asfd" is only 4 characters, so a space is used for padding.

Why does the guid not line up like the other rows?

You're trying to align the entire ID which is more than 5 columns, and that many characters can't "fit" into 5 columns.

How come when I specify {0,5} it starts printing after the 7th character column?

Where do you see that happening?

I assume what you want is to align everything up, so you can do this:

Console.WriteLine("{0,5}: {1}", "Id", person.Id.ToString());
Console.WriteLine("{0,5}: {1}", "Name", person.Name);
Console.WriteLine("{0,5}: {1}", "Phone", person.Phone);
Console.WriteLine("{0,5}: {1}", "Email", person.Email);

This will align all the field names together. This works because the longest field name is 5 characters long. You can change the ,5 to something else, and if they're all the same (and longer than 5) then all your field names will right-align by being padded with spaces on the left.

You can read more about it on MSDN here: http://msdn.microsoft.com/en-us/library/txafckwd%28v=vs.110%29.aspx

Align String Array to Columns

string[] str={"First","Second","Third","Forth","Fifth","Sixth","Seventh","Eighth","Ninth"};
for (int i=0;i<str.Length-2;i+=3)
Console.WriteLine ("{0,-10} {1,-10} {2,-10}",str[i],str[i+1],str[i+2]);

Demo Code

https://repl.it/repls/CelebratedMuffledCybernetics

How can I align the text with the text in the next line in console?

The format strings used in .NET accept an alignment component that allow you to specify the length of an argument and its alignment, eg:

Console.WriteLine("{0,5} {1,-10}",5,10);

will use 5 spaces for the first argument, right aligned and 10 spaces for the second argument, left aligned.

In your case you could write something like:

Console.WriteLine("{0,-25} {1,-15} {2,10}",name,number,section);

This will output name in columns 1-25 left aligned, number in 27-42 left aligned and section in 44 right aligned to 10 characters

The tricky part is that if the length of the formatted string is greater than the alignment length, the alignment is ignored. You can address that by first formatting each element before the final output statement, truncating them to the maximum allowed length.

Unfortunately, there is no way to center align the arguments. You'd have to calculate the length of each formatted string and pad it in code. The answers to this SO question use either a function to center-align the arguments, or a custom IFormattable that center-aligns the arguments of the format string.

How to pad multiple strings when writing to console so that part is aligned left and part is aligned right?

you can use String.Format + {index,length}

e.g:

Console.WriteLine(String.Format("{0,-10}  {1,-20}  ${2,-10} ${3,-10}", DateTime.Now, "Added Money", 10.00,10.00));
Console.WriteLine(String.Format("{0,-10} {1,-20} ${2,-10} ${3,-10}", DateTime.Now, "Cloud Popcorn A4", 10.00,6.35));
Console.WriteLine(String.Format("{0,-10} {1,-20} ${2,-10} ${3,-10}", DateTime.Now, "Cash Out", 6.35,0.00));

Aligning strings into columns

You can divide the total line width by the number of columns and pad each string to that length. You may also want to trim extra long strings. Here's an example that pads strings that are shorter than the column width and trims strings that are longer. You may want to tweak the behavior for longer strings:

    int Columns = 4;
int LineLength = 80;

public void WriteGroup(String[] group)
{
// determine the column width given the number of columns and the line width
int columnWidth = LineLength / Columns;

for (int i = 0; i < group.Length; i++)
{
if (i > 0 && i % Columns == 0)
{ // Finished a complete line; write a new-line to start on the next one
Console.WriteLine();
}
if (group[i].Length > columnWidth)
{ // This word is too long; truncate it to the column width
Console.WriteLine(group[i].Substring(0, columnWidth));
}
else
{ // Write out the word with spaces padding it to fill the column width
Console.Write(group[i].PadRight(columnWidth));
}
}
}

If you call the above method with this sample code:

var groupOfWords = new String[] { "alphabet", "alegator", "ant", 
"ardvark", "ark", "all", "amp", "ally", "alley" };
WriteGroup(groupOfWords);

Then you should get output that looks like this:

alphabet            alegator            ant                 ardvark
ark all amp ally
alley


Related Topics



Leave a reply



Submit