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

image_pdfimage_print

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; } } [/csharp]

This entry was posted in Data Types. Bookmark the permalink.