C#列格式 [英] C# Column formatting

查看:154
本文介绍了C#列格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一些格式化输出到控制台,但有一些问题的解决方案。
我做它在C#中,但一切时间我称之为Console.Write它打印整个事情到控制台的尽头,然后开始一个新行。因此,我想要做的就是它调整到四列,然后开始一个新行那里。

I'm trying to format some output to the console but having some problems with a solution. I'm doing it in C# but everything time I call Console.Write it prints the the entire thing to the very end of the console then starts a new line. So what I want to do is adjust it to four columns and then start a newLine there.

下面是正确的方式输出应该看起来像在控制台:

Here's the correct way the output should look like in the console:

Sam       John      Bob     Adam

Kelly     Nolan     Carl    Tim

Tom       David

下面是什么我的原来的样子,但它的错误的方式:

Here's whats mine turns out to look like but its the wrong way:

Sam    John    Bob    Adam  Kelly  Nolan   Carl   Tim

Tom    David

如果您有任何意见,请他们提供

If you have any ideas please provide them

推荐答案

我会写东西,管理的填充和布局。也许这样的事情?

I would write something that managed the padding and layout.. perhaps something like this?

class ConsoleColumnFormatter {
    private int _columnWidth = 20;
    private int _numColumns = 4;

    private int _currentColumn = 0;

    public ConsoleColumnFormatter(int numColumns, int columnWidth) {
        _numColumns = numColumns;
        _columnWidth = columnWidth;
    }

    public void Write(string str) {
        Console.Write(str.PadRight(_columnWidth - str.Length, ' '));
        _currentColumn++;

        checkForNewLine();
    }

    private void checkForNewLine() {
        if (_currentColumn >= _numColumns) {
            Console.Write("\n");
            _currentColumn = 0;
        }
    }
}

ConsoleColumnFormatter formatter = new ConsoleColumnFormatter(4, 20);

for (int i = 1; i <= 10; i++)
    formatter.Write("Column " + i.ToString());

..产生,这样的:

Column 1    Column 2    Column 3    Column 4
Column 5    Column 6    Column 7    Column 8
Column 9    Column 10

这篇关于C#列格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆