【问题标题】:How to add text wrapping or char limit on an already formatted string [duplicate]如何在已格式化的字符串上添加文本换行或字符限制[重复]
【发布时间】:2019-12-18 10:24:41
【问题描述】:

我已经编写了一些 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 个字符

【问题讨论】:

    标签: c# string.format character-limit


    【解决方案1】:

    您可以使用以下扩展名来限制 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);
    

    【讨论】:

    • 这太完美了!正是我需要解决我的问题非常感谢你指出我正确的方向:)
    猜你喜欢
    • 1970-01-01
    • 2013-05-12
    • 1970-01-01
    • 1970-01-01
    • 2015-11-27
    • 2015-10-22
    • 1970-01-01
    • 1970-01-01
    • 2014-10-01
    相关资源
    最近更新 更多