简体   繁体   中英

string formatting

I am trying to align values. I wonder why this happen :

        string value = "";

        value += string.Format("{0,-10}", "value");
        value += string.Format("{0,5}", "value");

        value += Environment.NewLine;

        value += string.Format("{0,-8}", "val");
        value += string.Format("{0,7}", "value");

        MessageBox.Show(value);

If i check value before i do "MessageBox.Show() it is correct . The result is:

value     value
val       value

As they should be, but when i do MessageBox.show() then they get like this :

   value     value
   val     value

I really cant understand why it changes the string with show()? Same thing happens when i am trying to print "value", then it doesnt align correct.

Btw: this is just a test code so you could understand the problem that i am having with the real code.

这是因为MessageBox.Show使用的字体没有固定的宽度...

This might be caused by the fact that the font used in the message box is not monospaced , meaning that each character takes an equal amount of horizontal space. The font you are using in the Visual Studio debugger probably is, which is why the padding looks entirely different.

You could try if using tabs instead of spaces for your formatting gives better results.

According to this answer the way to go is using \\t as a column seperator.

This definitely involves checking the length of all the words of each single column. This way you would know whether to use a single \\t or double \\t\\t etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM