合計行幅を列数で割り、各文字列をその長さにパディングできます。余分な長い文字列をトリミングすることもできます。列幅より短い文字列をパディングし、長い文字列をトリムする例を次に示します。より長い文字列の動作を微調整したい場合があります。
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