How would I get a code like this to keep everything formatted together?

Console.WriteLine("{0}\t{1}", name[j], score[j]);

When some of the names are longer and messes up the formatting so it outputs something like

Henrichson      100
Mike    80

Is there a way to make it so the scores are always in the same column?

有帮助吗?

解决方案

You can use String.PadRight() to make fixed column widths.

const int columnWidth = 15;

Console.WriteLine("{0} {1}", name[j].PadRight(columnWidth), score[j]);

columnWidth represents the target number of characters you want in the string. If the input string is less than the target, it will append spaces (by default).

Alternatively, you can make use of the built in format specifier options by adding a negative integer representing columnWidth as an argument in the specifer.

Console.WriteLine("{0,-15} {1}", name[j], score[j]);

其他提示

Use padding with proper max length, so rest will be filled with spaces:

Console.WriteLine("{0,-18}\t{1}", name[j], score[j]);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top