如何通过控制台对齐文本输出?

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已经包含了我可以使用的东西?

你是否提前拥有所有左列的值?如果是,你只需找到其中最长的一个并使用标准字符串格式化即可。 - Roman
不,它们是根据解析内容后的输入创建的。 - user1172635
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
*/

1
Linq是一种非常动态的可视化和处理数据的方式。使用IEnumerable的扩展方法,如Max以及Select的强大功能,可以将数据转换为独特的投影。我不再使用foreach语句进行编程,因为我只考虑使用扩展方法来操作数据列表。这非常强大。 - ΩmegaMan
是的,循环结构是为那些可能想在代码中产生副作用(如输出到屏幕或文件)的傻瓜准备的。 - Roman
垃圾进去...垃圾出来...结果可能因人而异。 - ΩmegaMan

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");
}

3
好的解决方案。建议: var padWidth = outputs.Max(o => o.Length) + 5;。 (说明:这是一行代码,意思是声明一个名为padWidth的变量,其值为所有outputs字符串中最长字符串的长度再加上5。) - Philip Fourie
啊,是的,确实更好。 - egbrad

2

您也可以参考这个页面来了解.NET字符串格式化。与手动使用PadLeftPadRight不同,您可以直接在格式化字符串中声明填充大小。例如:

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]*/ );
}

谢谢,这正是我所需要的。还可以告诉我使用哈希表键的最有效方法吗?目前我正在使用CopyTo方法将散列表中的键转储到字符串数组中,然后在数组上使用您发布的代码。有没有办法在不先把它们放在数组中的情况下完成这个操作? - user1172635
2
除非你的目标是 .NET 1.1 代码(或者你正在使用一个这样的框架),否则你应该使用 Dictionary 而不是 Hashtable。如果你绝对必须使用 HashTable,在 MSDN 上有一个直接遍历它的示例。我也强烈建议养成在提问之前先在 MSDN 上查找资料的习惯。 - Roman

0
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;

    namespace ConsoleApplication1
    {
     class Program
    {
    static void Main(string[] args)
    {

        string[] lines = File.ReadAllLines("E:\\Exp2Act1.txt");

        int what1 = (Console.WindowWidth / 2) - 18;
        int here1 = (Console.WindowHeight / 3);
        Console.SetCursorPosition(what1, here1);
        Console.WriteLine(lines[0]);
        int what2 = (Console.WindowWidth / 2) - 18;
        int here2 = (Console.WindowHeight / 3) + 1;
        Console.SetCursorPosition(what2, here2);
        Console.WriteLine(lines[1]);
        int what3 = (Console.WindowWidth / 2) - 18;
        int here3 = (Console.WindowHeight / 3) + 2;
        Console.SetCursorPosition(what3, here3);
        Console.WriteLine(lines[2]);
        int what4 = (Console.WindowWidth / 2) - 18;
        int here4 = (Console.WindowHeight / 3) + 3;
        Console.SetCursorPosition(what4, here4);
        Console.WriteLine(lines[3]);
        int what5 = (Console.WindowWidth / 2) - 18;
        int here5 = (Console.WindowHeight / 3) + 4;
        Console.SetCursorPosition(what5, here5);
        Console.WriteLine(lines[4]);
        int what6 = (Console.WindowWidth / 2) - 18;
        int here6 = (Console.WindowHeight / 3) + 5;
        Console.SetCursorPosition(what6, here6);
        Console.WriteLine(lines[5]);
        Console.Read();
    }
}

}


那是我的答案,但我无法使 (*) 对齐,我该怎么办? - Christine Joy Olmilla

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接