String padding problem

让人想犯罪 __ 提交于 2019-12-11 19:15:38

问题


Using the code given below the padding doesn't seem to be playing as it should, in theory the text "ADD this text" should start from column 21 in both the strings but in str2 it has a few extra spaces. On checking the length of both the strings the length turned out to be the same 20 as expected.

        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);


Anybody encountered this problem before? Is there something obvious I am missing.

Many Thanks.


回答1:


Maybe your MessageBox is showing variable-pitch font?

Try setting the font to Courier New (in any relevant control), and see if it helps.




回答2:


Change your code to:

    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);

That way you will see if the right number of characters are being padded correctly and you will also be able to tell if it is a font width issue as other have stated.



来源:https://stackoverflow.com/questions/763257/string-padding-problem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!