I have written some c# code that takes a csv file and displays in the console, I have used string.format to align both my heading and my column data however I have one string of data in a columns that it significantly longer in characters than the rest causing issue with alignment. Could someone either let me know if I can wrap text or add a character limit to my column named "boat name"
I have tried putting my current string.Format for DisplayMembers() into a variable and adding limit (0, 12) to this but it failed.
public static void DisplayHeadings()
{
Console.WriteLine(string.Format("{0,-4} {1,-7} {2,-10} {3,-8} {4,-20} {5,-8} {6,-10} {7,-6} {8,-6} {9, -9} {10, -5}"
, "Pos", "BoatID", "Waterway", "Reg No", "Boat Name", "Length", "Homewater", "Beam", "Year", "Prop Pwr", "Prop"));
}
//string limit5 = "The quick brown fox jumped over the lazy dog.".LimitLength(5);
public static void DisplayMembers()
{
position = 1;
foreach (var boat in boats)
{
Console.WriteLine(string.Format("{0,-4} {1,-7} {2,-10} {3,-8} {4,-20} {5,-8} {6,-10} {7,-6} {8,-6} {9, -9} {10, -5}",
position,
boat.BoatId,
boat.Waterway,
boat.RegNo,
boat.BoatName,
boat.BoatLength,
boat.HomeWaterway,
boat.BoatBeam,
boat.Year,
boat.PropulsionPower,
boat.Propulsion));
position++;
// this all works and aligns as I want however boat.BoatName has one record which is about 30 characters compared to the others at around 10-12 chars.
limit chars on boat.BoatName to around 15 characters
You could use the following extension to limit the BoatName string.
public static class StringExts
{
public static string CutStringIfNeeded(this string value, int maxCount)
{
return (!string.IsNullOrWhiteSpace(value) && value.Length >= maxCount)
? value.Substring(0, maxCount - 1)
: value;
}
}
Usage:
// returns the limited string or original one if less than 15 chars.
boat.BoatName.CutStringIfNeeded(15);