C# - How to Properly Indent String Data with Tabs?

2019-07-26 23:34发布

In my C# Console program I have 4 variables. Their names and types are as follows:

int ID
bool Status
bool Available
int Count

I would like to be able to print them to the Console, nicely indented as follows:

Indented (Required)

However, when I use the tabs "\t", to format my string, it does not take into account the text width, and all the values are indented waywardly as follows:

Wayward (Actual result)

How do I fix this? I don't want to use any third party libraries, but simply .NET functionality such as String.Format().

2条回答
贼婆χ
2楼-- · 2019-07-26 23:54

Try a padding

 var data = new string[5,4]
            {
                 { "ID", "Status", "Available", "Count" },
                { "------", "------", "------", "------" },
                { "1123", "True", "False", "-1" },
                { "23", "False", "True", "-23" },
                { "3", "True", "True", "-1" }

            };
            for (int i = 0; i < data.GetLength(0); i++)
            {
                Console.WriteLine("{0,-10}\t{1,-10}\t{2,-10}\t{3,-10}", data[i, 0], data[i, 1], data[i, 2], data[i, 3]);

            }
查看更多
太酷不给撩
3楼-- · 2019-07-27 00:03

You can pad them with spaces like this:

Console.WriteLine("{0,-10}\t{1,-5}\t{2,-5}\t{3,-10}", ID, Status, Available, Count);

And if you want to right-align them instead:

Console.WriteLine("{0,10}\t{1,5}\t{2,5}\t{3,10}", ID, Status, Available, Count);

I set the padding to the longest possible length of an integer or boolean represented in string form. You may have to adjust it to account for your column titles.

查看更多
登录 后发表回答