2020年8月24日 星期一

Alignment and spacing using String.Format (轉貼)

 

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. 
  1. 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. 
  1. Console.WriteLine("***** Alignment ****/");  
  2. string[] books = {"A Programmer's Guide to ADO.NET""Graphics Programming""Programming C#"};  
  3. string[] publishers = {"APress""Addision Wesley""C# Corner" };  
  4. decimal[] prices = { 45.95m, 54.95m, 49.95m };  
  5. int[] years = { 2001, 2002, 2003 };  
  6.   
  7. Console.WriteLine("Mahesh Chand's Books");  
  8. String data = String.Format("{0,-35} {1,-20} {2,-10} {3, -10} \n",  
  9. "Title""Publisher""Price""Year");  
  10. for (int index = 0; index < years.Length; index++)  
  11. data += String.Format("{0,-35} {1,-20} {2, -10} {3, -10} \n",  
  12. books[index], publishers[index], prices[index], years[index]);  
  13. Console.WriteLine($"\n{data}");  

沒有留言:

張貼留言