0

我已经编写了一些 c# 代码,它获取一个 csv 文件并显示在控制台中,我使用 string.format 来对齐我的标题和我的列数据,但是我在一列中有一个数据字符串,它的字符比休息导致对齐问题。有人可以告诉我是否可以换行或在名为“船名”的列中添加字符限制

我尝试将我当前的 string.Format for DisplayMembers() 放入一个变量中,并在其中添加限制 (0, 12) 但它失败了。

   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++;

// 这一切都可以按我的意愿工作和对齐,但是boat.BoatName 有一个记录,大约 30 个字符,而其他记录大约 10-12 个字符。

将boat.BoatName 上的字符限制为大约 15 个字符

4

1 回答 1

0

您可以使用以下扩展名来限制 BoatName 字符串。

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;
    }
}

用法:

// returns the limited string or original one if less than 15 chars.
boat.BoatName.CutStringIfNeeded(15);
于 2019-08-11T15:52:25.697 回答