首页 > 解决方案 > 问题:有没有办法在 C# 中像这样格式化空白?

问题描述

有没有办法在 C# 中像这样格式化空白?

我想知道你是否可以将字符串数组解析成一个方法并让它返回一个带空格的格式化字符串,我需要一种特定的方式来完成,所以这里有一个例子:

string[][] StringArray = new string[][] {
    new string[] {"Name:", "John Jones."}
    new string[] {"Date of birth:", "07/11/1989."}
    new string[] {"Age:", "29 Years old."}
};

FormatWhiteSpace(StringArray, Padding: 5);

输出将是:

Name:              John Jones.
Date of birth:     07/11/1989.
Age:               29 Years old.

正如您在上面的输出中看到的那样,所有内容都排成一行,并有 5 个空格用于填充,正如我们调用该方法时所定义的那样。这正是我们想要的。我们还有一个二维数组,因为它允许我们一次解析超过 1 行。这是另一个示例,这次有两列以上:

string[][] StringArray = new string[][] {
    new string[] {"Name:", "John", "Jones."}
    new string[] {"Date of birth:", "Monday,", "07/11/1989."}
    new string[] {"Age:", "29", "Years old."}
};

FormatWhiteSpace(StringArray, Padding: 2);

第二个输出是:

Name:           John     Jones.
Date of birth:  Monday,  07/11/1989.
Age:            29       Years old.

这就是我想知道的全部,如果您知道任何可以帮助我的事情,请告诉我。谢谢你们的帮助,你们真的让我很开心。

标签: c#formattingwhitespace

解决方案


尝试这样的事情(我在您的数据中添加了一个额外的行以使其不方形并使调试更加明显):

public static class PaddedColumns
{
    private static string[][] _stringArray = new string[][] {
        new [] {"Name:", "John", "Jones."},
        new [] {"Date of birth:", "Monday,", "07/11/1989."},
        new [] {"Age:", "29", "Years old."},
        new [] {"Eye Color:", "blue", ""},
    };

    public static void PadIt()
    {
        OutputPadded(_stringArray);
    }

    public static void OutputPadded(string[][] strings)
    {
        var columnMaxes = new int[strings[0].Length];

        foreach (var row in strings)
        {
            for (var colNo = 0; colNo < row.Length; ++colNo)
            {
                if (row[colNo].Length > columnMaxes[colNo])
                {
                    columnMaxes[colNo] = row[colNo].Length;
                }
            }
        }

        const int extraPadding = 2;

        //got the maxes, now go through and use them to pad things
        foreach (var row in strings)
        {
            for (var colNo = 0; colNo < row.Length; ++colNo)
            {
                Console.Write(row[colNo].PadRight(columnMaxes[colNo] + extraPadding));
            }
            Console.WriteLine("");
        }

    }

}

结果如下所示:

Name:           John     Jones.
Date of birth:  Monday,  07/11/1989.
Age:            29       Years old.
Eye Color:      blue

推荐阅读