C# Column formatting

后端 未结 5 1811
失恋的感觉
失恋的感觉 2021-01-07 09:27

I\'m trying to format some output to the console but having some problems with a solution. I\'m doing it in C# but everything time I call Console.Write it prints the the ent

5条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-07 09:35

    if i understood your question .I have used below technique for printing out a table in Txt (log file) in console.

    The trick is to use the String.format

    // Example from - http://msdn.microsoft.com/en-us/library/system.string.format.aspx
    
    
    
    using System;
    
    public class Example
    {
       public static void Main()
       {
          // Create array of 5-tuples with population data for three U.S. cities, 1940-1950.
          Tuple[] cities = 
              { Tuple.Create("Los Angeles", new DateTime(1940, 1, 1), 1504277, 
                             new DateTime(1950, 1, 1), 1970358),
                Tuple.Create("New York", new DateTime(1940, 1, 1), 7454995, 
                             new DateTime(1950, 1, 1), 7891957),  
                Tuple.Create("Chicago", new DateTime(1940, 1, 1), 3396808, 
                             new DateTime(1950, 1, 1), 3620962),  
                Tuple.Create("Detroit", new DateTime(1940, 1, 1), 1623452, 
                             new DateTime(1950, 1, 1), 1849568) };
    
          // Display header 
          string header = String.Format("{0,-12}{1,8}{2,12}{1,8}{2,12}{3,14}\n",
                                        "City", "Year", "Population", "Change (%)");
          Console.WriteLine(header);
          string output;      
          foreach (var city in cities) {
             output = String.Format("{0,-12}{1,8:yyyy}{2,12:N0}{3,8:yyyy}{4,12:N0}{5,14:P1}",
                                    city.Item1, city.Item2, city.Item3, city.Item4, city.Item5,
                                    (city.Item5 - city.Item3)/ (double)city.Item3);
             Console.WriteLine(output);
          }
       }
    }
    // The example displays the following output: 
    //    City            Year  Population    Year  Population    Change (%) 
    //     
    //    Los Angeles     1940   1,504,277    1950   1,970,358        31.0 % 
    //    New York        1940   7,454,995    1950   7,891,957         5.9 % 
    //    Chicago         1940   3,396,808    1950   3,620,962         6.6 % 
    //    Detroit         1940   1,623,452    1950   1,849,568        13.9 %
    

提交回复
热议问题