Jun 24, 2012

(C#) Align String with Spaces

1 comment

 Align String with Spaces

This example shows how to align strings with spaces. The example formats text to table and writes it to console output.

To align string to the right or to the left use static method String.Format. To align string to the left (spaces on the right) use formatting patern with comma (,) followed by a negative number of characters: String.Format("{0,–10}", text). To right alignment use a positive number: {0,10}.
Following example shows how to format text to the table. Values in the first and second column are aligned to the left and the third column is aligned to the right.

Code:
Console.WriteLine("-------------------------------");
Console.WriteLine("First Name | Last Name  |   Age");
Console.WriteLine("-------------------------------");
Console.WriteLine(String.Format("{0,-10} | {1,-10} | {2,5}", "AAAA", "AAAAA", 25));
Console.WriteLine(String.Format("{0,-10} | {1,-10} | {2,5}", "BBBB", "BBBBBB", 26));
Console.WriteLine(String.Format("{0,-10} | {1,-10} | {2,5}", "CCCCC", "CCC", 27));
Console.WriteLine("-------------------------------");

Output string:
 -------------------------------
 First Name | Last Name  |   Age
 -------------------------------
 AAAA       | AAAAA      |    25
 BBBB       | BBBBBB     |    26
 CCCCC      | CCC        |    27
 -------------------------------


If you feel this is helpful or you like it, Please share this using share buttons available on page.

1 comment :