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

纵然是瞬间 提交于 2020-01-06 03:49:06

问题


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:

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:

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


回答1:


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.




回答2:


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]);

            }


来源:https://stackoverflow.com/questions/36109915/c-sharp-how-to-properly-indent-string-data-with-tabs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!