1

我有一组字符串,用户可以添加或从中减去。我需要一种方法来打印列中的字符串,以便每个字符串的第一个字母对齐。但是,我必须在运行时更改列数。尽管默认值为 4 列,但用户可以选择 1 到 6 之间的任何数字。我不知道如何将未知数量的字符串格式化为未知数量的列。

示例输入: it we so be aioutyzc yo bo go an

四列的示例输出

带有 2 个字母的“单词”:

我们就是这样

哟波去

带有 1 个字母的“单词”:

艾欧

tyzc

注意:不用担心解析我的代码中已经包含的单词,如果有帮助我可以添加。

4

2 回答 2

2

如果您尝试创建固定宽度的列,则可以在创建行时使用string.PadLeft(paddingChar, width)和。string.PadRight(paddingChar, width)

http://msdn.microsoft.com/en-us/library/system.string.padleft.aspx

您可以遍历您的单词并在每个单词上调用 .PadXXXX(width) 。它会自动用正确数量的空格填充您的单词,以使您的字符串具有您提供的宽度。

于 2012-11-11T01:35:44.547 回答
1

您可以将总行宽除以列数并将每个字符串填充到该长度。您可能还想修剪超长的字符串。这是一个填充比列宽短的字符串并修剪更长的字符串的示例。您可能需要调整较长字符串的行为:

    int Columns = 4;
    int LineLength = 80;

    public void WriteGroup(String[] group)
    {
        // determine the column width given the number of columns and the line width
        int columnWidth = LineLength / Columns;

        for (int i = 0; i < group.Length; i++)
        {
            if (i > 0 && i % Columns == 0)
            {   // Finished a complete line; write a new-line to start on the next one
                Console.WriteLine();
            }
            if (group[i].Length > columnWidth)
            {   // This word is too long; truncate it to the column width
                Console.WriteLine(group[i].Substring(0, columnWidth));
            }
            else
            {   // Write out the word with spaces padding it to fill the column width
                Console.Write(group[i].PadRight(columnWidth));
            }
        }
    }

如果您使用此示例代码调用上述方法:

var groupOfWords = new String[] { "alphabet", "alegator", "ant", 
    "ardvark", "ark", "all", "amp", "ally", "alley" };
WriteGroup(groupOfWords);

然后你应该得到如下所示的输出:

alphabet            alegator            ant                 ardvark
ark                 all                 amp                 ally
alley
于 2012-11-11T01:37:42.233 回答