Left justify and align a set of strings to improve the appearance of program output. - CSharp Language Basics

CSharp examples for Language Basics:Data Type Format

Description

Left justify and align a set of strings to improve the appearance of program output.

Demo Code

using System;/*from   w w  w. j  av a  2s .  c om*/
using System.Collections.Generic;
class Program
{
   public static void Main(string[] args)
   {
      List<string> names = new List<string> {"test","  test","test test","Sam"," abc"};
      Console.WriteLine("The following names are of " + "different lengths");
      foreach(string s in names)
      {
         Console.WriteLine("This is the name '" + s + "' before");
      }
      List<string> stringsToAlign = new List<string>();
      for (int i = 0; i < names.Count; i++)
      {
         string trimmedName = names[i].Trim();
         stringsToAlign.Add(trimmedName);
      }
      int maxLength = 0;
      foreach (string s in stringsToAlign)
      {
         if (s.Length > maxLength)
         {
            maxLength = s.Length;
         }
      }
      for (int i = 0; i < stringsToAlign.Count; i++)
      {
         stringsToAlign[i] = stringsToAlign[i].PadRight(maxLength + 1);
      }
      Console.WriteLine("The following are the same names " + "normalized to the same length");
      foreach(string s in stringsToAlign)
      {
         Console.WriteLine("This is the name '" + s + "' afterwards");
      }
   }
}

Result


Related Tutorials