C# 字符串格式不一致

发布于 2024-11-14 22:11:05 字数 503 浏览 0 评论 0原文

我正在尝试构建许多排列良好的字符串,但格式设置并未按我预期的方式工作。

如果我有:

String.Format("{0,-25}{1,-7}{2,-18}{3,-8}{4,-15}{5,-3}{6,-10}",
              i.Name, "Price: ", i.Price.toString(), "Weight: ",
              i.Weight.toString() + " lbs", "Quantity:",i.Quantity.toString()));

我希望获得从行首开始的名称(这是一个字符串),然后是从第 26 个字符开始的“价格”,依此类推。 (所有名称均不超过 10 个字符)。相反,第二列到处都是,具体取决于名称的长度。

我也使用 StringBuilder 进行了尝试,得到了相同的结果。许多互联网搜索只是显示看起来与我的代码几乎相同的代码,所以我不确定什么不起作用。

编辑:修复错别字

I'm trying to build a number of strings that line up nicely, but the formatting isn't working the way I would expect.

If I have:

String.Format("{0,-25}{1,-7}{2,-18}{3,-8}{4,-15}{5,-3}{6,-10}",
              i.Name, "Price: ", i.Price.toString(), "Weight: ",
              i.Weight.toString() + " lbs", "Quantity:",i.Quantity.toString()));

I would expect to get Name (which is a string) starting at the beginning of the line, then "Price" starting at character 26, and so on. (None of the names are more than 10 characters). Instead, the second column is all over the place depending on the length of name.

I tried this using a StringBuilder as well, with the same result. A number of internet searches are just showing code that looks pretty much the same as what I have, so I'm not sure what's not working.

Edit: fixed typos

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

世态炎凉 2024-11-21 22:11:05

我怀疑问题在于显示而不是字符串本身。这些对齐方式仅在字体为等宽字体时才有效。等宽字体是每个字符宽度相同的字体。其中有几个是随 Windows、Office、Visual Studio 提供的。许多人认为“Consolas”是最好的。

我建议您更改向 Consolas 显示数据的任何控件的字体。

I suspect that the problem is the display rather than the strings themselves. These sorts of alignments only work when the font is a monospace font. A monospace font is one in which each character is the same width. There are several of these provided with Windows,Office, Visual Studio. Many people consider "Consolas" to be the best.

I recommend you change the font of whatever control is displaying your data to Consolas.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文