1

ユーザーが追加または削除できる文字列のコレクションがあります。各文字列の最初の文字が整列するように、文字列を列に出力する方法が必要です。ただし、実行時に列数を変更できる必要があります。デフォルトは 4 列ですが、1 から 6 までの任意の数を選択できます。不明な数の文字列を不明な数の列にフォーマットする方法がわかりません。

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

4 列の出力例

2文字の「言葉」:

私たちもそうです

ヨボゴーアン

1文字の「言葉」:

あいおう

tyzc

注:コードに既にある単語の解析について心配する必要はありません。役立つ場合は追加できます。

4

2 に答える 2

2

固定幅の列を作成しようとしている場合は、行を作成するときにstring.PadLeft(paddingChar, width)andを使用できます。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 に答える