格式化字符串“溢出”列

时间:2016-05-06 05:50:09

标签: c#

我是C#的新手,我无法弄清楚要搜索什么。我正在尝试在另一个字符串列表右侧的“列”中打印字符串列表。右侧“列”中的两个字符串具有多个值,每个值都需要自己的行。但是当我尝试这样做时,需要自己的行的值最终会在左边结束,而不是留在他们的“列”中。

以下是我想看到的内容:

这就是我得到的:

这是我的代码:

static void Main(string[] args)
{
    string ut = "1Y, 4D, 01:23:45";
    string met = "T+4D, 01:11:32";
    string vesselName = "Saturn K";
    string vesselModules = "Command/Service Module \nMunar Excursion Module";
    string kerbals = "Valentina Kerman, Pilot; \nJebediah Kerman, Pilot; \nBill Kerman, Engineer; \nBob Kerman, Scientist";

    string[] headerNames = { "UT:", "MET:", "Vessel:", "Modules:", "Crew:" };
    string[] headerData = new string[5] { ut, met, vesselName, vesselModules, kerbals };

    for (int index = 0; index < headerNames.Length; index++)
        Console.WriteLine("{0,-12} {1,-46}", headerNames[index], headerData[index]);
}

4 个答案:

答案 0 :(得分:0)

这里的问题是你的vesselModuleskerbals\n导致代码移到新行,所以\n从第0列开始。所以如果你尝试删除\n它会正常工作。

答案 1 :(得分:0)

您可以在数组中拆分这些字符串,并使用嵌套循环在换行符中打印这些字符串。

static void Main(string[] args)
{
    string ut = "1Y, 4D, 01:23:45";
    string met = "T+4D, 01:11:32";
    string vesselName = "Saturn K";
    string vesselModules = "Command/Service Module \nMunar Excursion Module";
    string kerbals = "Valentina Kerman, Pilot; \nJebediah Kerman, Pilot; \nBill Kerman, Engineer; \nBob Kerman, Scientist";

    string[] headerNames = { "UT:", "MET:", "Vessel:", "Modules:", "Crew:" };
    string[] headerData = new string[5] { ut, met, vesselName, vesselModules, kerbals };

     for (int index = 0; index < headerNames.Length; index++) {
         if(headerNames[index] == "Modules:" || headerNames[index] == "Crew:") {
            string dataStr = headerData[index];
            var data = dataStr.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
            Console.WriteLine("{0,-12} {1,-46}", headerNames[index], data[0] ?? string.Empty);
            for (int i = 1; i < data.Length; i++) {
                Console.WriteLine("{0,-12} {1,-46}", string.Empty, data[i]);
            }
         } else {
            Console.WriteLine("{0,-12} {1,-46}", headerNames[index], headerData[index]);
         }
    }
}

答案 2 :(得分:0)

问题是你在一列中有几个项目。通过拆分项而不是创建新行,可以轻松解决此问题。请注意,我使用;代替\n

    string ut = "1Y, 4D, 01:23:45";
    string met = "T+4D, 01:11:32";
    string vesselName = "Saturn K";
    string vesselModules = "Command/Service Module;Munar Excursion Module";
    string kerbals = "Valentina Kerman, Pilot;Jebediah Kerman, Pilot;Bill Kerman, Engineer;Bob Kerman, Scientist";

    string[] headerNames = { "UT:", "MET:", "Vessel:", "Modules:", "Crew:" };
    string[] headerData = new string[5] { ut, met, vesselName, vesselModules, kerbals };
    for (int index = 0; index < headerNames.Length; index++)
    {
        // Split data if there are more than one.
        var items = headerData[index].Split(';');
        if (items.Length > 1)
        {
            // We got more than one item. Render first item.
            Console.WriteLine("{0,-12} {1,-46}", headerNames[index], items[0]);
            for (int i = 1; i < items.Length; i ++)
            {
                // Render the following items.
                Console.WriteLine("{0,-12} {1,-46}", string.Empty, items[i]);
            }

        }
        else
        {
            // Only one item. Render it as usual.
            Console.WriteLine("{0,-12} {1,-46}", headerNames[index], headerData[index]);
        }
    }

enter image description here

根据评论进行修改:

Console.WriteLine使用string.Format()模式。来自Console

// Writes out a formatted string and a new line.  Uses the same 
// semantics as String.Format.
// 
public virtual void WriteLine (String format, params Object[] arg)
{
    WriteLine(String.Format(FormatProvider, format, arg));
}

基本上说,用传递的参数替换每个{}。您可以将{}视为占位符。我只是说应该使用空值。

示例:

Console.WriteLine("{0} - {1} - {2}", "One", "Two", "Three");

输出:

One - Two - Three

这与问题中的示例非常相似,但问题还定义了应使用{0,-12}显示的字符数。我所做的就是简单地传递一个空字符串,例如&#34;&#34;。

Console.WriteLine("{0} - {1} - {2}", "One", string.Empty, "Three");

输出:

One -  - Three

在我的代码中,我只是说前12个字符不应该被任何内容替换,但仍然使用12个字符:

Console.WriteLine("{0,-12} {1,-46}", string.Empty, "Some value");

您可以在此处阅读有关string.Format的更多信息:

http://www.dotnetperls.com/format

关于增量,我所做的是用你的值填充一个数组。如果我发现它不止一个值,我知道第二行(以及所有以下内容)应该有一个&#34;空标题&#34;。通过将string.Empty传递给Console.WriteLine,它将呈现一个空标题(但仍然是标题)。

伪代码:

Split by ';'.
Is there more than one item? If yes, goto 1. If no, goto 2.

1. Render first line with header and first data.
1.1 Render all the other lines, but with an empty header (still taking up 12 chars).

2. Render line with header and data.

答案 3 :(得分:0)

我会像我的例子那样解决它。在顶部,您可以定义列分隔符和表格宽度

class Program
{
    static int tableWidth = 77;
    static string columnSeparator = string.Empty;

    static void Main(string[] args)
    {
        string ut = "1Y, 4D, 01:23:45";
        string met = "T+4D, 01:11:32";
        string vesselName = "Saturn K";
        string vesselModules = "Command/Service Module \nMunar Excursion Module";
        string kerbals = "Valentina Kerman, Pilot; \nJebediah Kerman, Pilot; \nBill Kerman, Engineer; \nBob Kerman, Scientist";

        string[] headerNames = { "UT:", "MET:", "Vessel:", "Modules:", "Crew:" };
        string[] headerData = new string[5] { ut, met, vesselName, vesselModules, kerbals };

        for (int index = 0; index < headerNames.Length; index++)
        {
            var multiCol = headerData[index].Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
            int counter = 0;
            foreach (var col in multiCol)
            {
                PrintRow(new string[] { counter == 0 ? headerNames[index] : string.Empty, col });
                counter++;
            }
        }

        Console.Read();
    }

    static void PrintRow(params string[] columns)
    {
        int width = (tableWidth - columns.Length) / columns.Length;
        string row = columnSeparator;

        foreach (string column in columns)
        {
            row += AlignLeft(column, width) + columnSeparator;
        }

        Console.WriteLine(row);
    }

    static string AlignCentre(string text, int width)
    {
        text = text.Length > width ? text.Substring(0, width - 3) + "..." : text;

        if (string.IsNullOrEmpty(text))
        {
            return new string(' ', width);
        }
        else
        {
            return text.PadRight(width - (width - text.Length) / 2).PadLeft(width);
        }
    }

    static string AlignLeft(string text, int width)
    {
        text = text.Length > width ? text.Substring(0, width - 3) + "..." : text;

        if (string.IsNullOrEmpty(text))
        {
            return new string(' ', width);
        }
        else
        {
            return text.PadRight(width);
        }
    }
}