字符串格式化
我正在努力调整价值观。 我想知道为什么会发生这种情况:
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);
如果我在执行“MessageBox.Show()之前检查值,它是正确。结果是:
value value
val value
它们应该是这样,但是当我这样做时MessageBox.show() 然后他们会这样:
value value
val value
我真的无法理解为什么它用 show() 更改字符串?当我尝试打印“值”时会发生同样的事情,然后它不正确对齐
:这只是一个 。测试代码,以便您可以理解我遇到的问题与真实的代码一起。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这可能是由于消息框中使用的字体不是 等宽 造成的,这意味着每个字符占用相同的水平空间。您在 Visual Studio 调试器中使用的字体可能是,这就是填充看起来完全不同的原因。
如果使用制表符而不是空格进行格式设置可以提供更好的结果,您可以尝试。
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.
那是因为
MessageBox.Show
使用的字体没有固定宽度......That's because the font used by
MessageBox.Show
doesn't have a fixed width...根据 this 回答要走的路使用
\t
作为列分隔符。这肯定涉及检查每一列的所有单词的长度。这样您就知道是使用单个
\t
还是双\t\t
等。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.