4

私がやりたいことは、Console.Writeline メソッドを介して出力するテキストを、長さに関係なく完全に整列させることです。

Example:
// Notice that no matter the length of the text on the left, 
// the text on the right is always spaced at least 5 spaces.

    this is output          text
    this is also output     text
    output                  text
    my output               text

これには独自のメソッドを作成する必要がありますか、それとも .Net には既に使用できるものが含まれていますか?

4

4 に答える 4

3

代わりにLinqで考えてください!

var outputs = new List<string>() {
                        "this is output",
                        "this is also output",
                        "output",
                        "my output"
                    };

var size = outputs.Max (str => str.Length) + 5;

Console.WriteLine ( 
           string.Join(Environment.NewLine, 
                       outputs.Select (str => str.PadRight( size ) + "Text" ) )
                   );

/*
this is output          Text
this is also output     Text
output                  Text
my output               Text
*/
于 2012-04-24T19:48:47.217 に答える
2

このようなものがうまくいくはずです。うまくいけば、それをあなたのニーズに適応させることができます.

string[] outputs = {
                        "this is output",
                        "this is also output",
                        "output",
                        "my output"
                    };

// order outputs in descending order by length
var orderedOutputs = outputs.OrderByDescending(s => s.Length);

// get longest output and add 5 chars
var padWidth = orderedOutputs.First().Length + 5;

foreach (string str in outputs)
{
    // this will pad the right side of the string with whitespace when needed
    string paddedString = str.PadRight(padWidth);
    Console.WriteLine("{0}{1}", paddedString, "text");
}
于 2012-04-24T18:24:54.893 に答える
2

.NET 文字列の書式設定について説明しているこのページもご覧ください。PadLeftマニュアルの代わりに、PadRightフォーマット文字列でパディング サイズを直接宣言できます。の線に沿った何か

var offset = outputs.Max( s => s.Length );
var formatString = "{0,-" + offset + "}     {1}";

foreach( var dataPoint in /*[your collection of data points]*/ )
{
    Console.WriteLine( formatString, /*[first value]*/, /*[second value]*/ );
}
于 2012-04-24T18:53:00.620 に答える