left justify and align a set of strings to improve the appearance of program output : String Format : Data Types C# Source Code


Custom Search

C# Source Code » Data Types » String Format »

 

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








    
 

using System;

class Class1 {
    public static void Main(string[] args) {
        string[] names = {"CA  ","  SA","J      A","SA"," SA "};

        foreach (string s in names) {
            Console.WriteLine("This is the name '{0}' before", s);
        }
        string[] sAlignedNames = TrimAndPad(names);

        foreach (string s in sAlignedNames) {
            Console.WriteLine("This is the name '{0}' afterwards", s);
        }
    }

    public static string[] TrimAndPad(string[] strings) {
        string[] stringsToAlign = new String[strings.Length];

        for (int i = 0; i < stringsToAlign.Length; i++) {
            stringsToAlign[i] = strings[i].Trim();
        }

        int nMaxLength = 0;
        foreach (string s in stringsToAlign) {
            if (s.Length > nMaxLength) {
                nMaxLength = s.Length;
            }
        }
        for (int i = 0; i < stringsToAlign.Length; i++) {
            stringsToAlign[i] =
                  stringsToAlign[i].PadRight(nMaxLength + 1);
        }

        return stringsToAlign;
    }
}

 
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo Data Types
» String Format