【问题标题】:String padding problem字符串填充问题
【发布时间】:2010-10-20 06:43:39
【问题描述】:

使用填充下面给出的代码似乎没有按应有的方式播放,理论上文本 "ADD this text" 应该从两个字符串的第 21 列开始,但在 str2 中有一些额外的空间。在检查两个字符串的长度时,长度结果与预期的相同 20。

        string str1 = "Test".PadRight(20);
        string str2 = "Test123".PadRight(20);

        string common = "Add this text";

        MessageBox.Show(str1.Length.ToString());
        MessageBox.Show(str2.Length.ToString());

        MessageBox.Show(str1 + common + "\n" + str2 + common);


以前有人遇到过这个问题吗?我有什么明显的遗漏吗?

非常感谢。

【问题讨论】:

    标签: c# string padding


    【解决方案1】:

    将您的代码更改为:

        string str1 = "Test".PadRight(20, 'W');
        string str2 = "Test123".PadRight(20, 'I');
        string common = "Add this text";
        MessageBox.Show(str1.Length.ToString());
        MessageBox.Show(str2.Length.ToString());
        MessageBox.Show(str1 + common + "\n" + str2 + common);
    

    这样您将看到是否正确填充了正确数量的字符,并且您还可以判断这是否是其他人所说的字体宽度问题。

    【讨论】:

      【解决方案2】:

      也许您的 MessageBox 正在显示可变间距字体?

      尝试将字体设置为Courier New(在任何相关控件中),看看是否有帮助。

      【讨论】:

      • 同样的事情发生在 TextBox、TextBlock 等中。
      • 在 TextBox、TextBlock 等中使用等宽字体(等宽)
      猜你喜欢
      • 2020-11-20
      • 2019-11-19
      • 1970-01-01
      • 2011-09-07
      • 1970-01-01
      • 2019-06-12
      • 2013-07-16
      • 2010-10-19
      • 2016-03-13
      相关资源
      最近更新 更多