Alignment and spacing using String.Format
Besides the index, alignment and formatString are two optional arguments of String.Format method. Alignment is followed by index and separated by a comma as you can see in the following syntax.
- String.Format("{index[,alignment][:formatString]}", object);
By default, strings are right-aligned within their field if you specify a field width. To left-align strings in a field, you preface the field width with a negative sign, such as {0,-12} to define a 12-character right-aligned field.
The following code example in Listing 3 creates a formatted table of items with spacing between items that displays a list of published books with their title, price, publisher, and year published.
- Console.WriteLine("***** Alignment ****/");
- string[] books = {"A Programmer's Guide to ADO.NET", "Graphics Programming", "Programming C#"};
- string[] publishers = {"APress", "Addision Wesley", "C# Corner" };
- decimal[] prices = { 45.95m, 54.95m, 49.95m };
- int[] years = { 2001, 2002, 2003 };
- Console.WriteLine("Mahesh Chand's Books");
- String data = String.Format("{0,-35} {1,-20} {2,-10} {3, -10} \n",
- "Title", "Publisher", "Price", "Year");
- for (int index = 0; index < years.Length; index++)
- data += String.Format("{0,-35} {1,-20} {2, -10} {3, -10} \n",
- books[index], publishers[index], prices[index], years[index]);
- Console.WriteLine($"\n{data}");
沒有留言:
張貼留言