【问题标题】:I need something in c# which work like the setw() in c++我需要 c# 中的一些东西,就像 c++ 中的 setw()
【发布时间】:2012-03-29 05:26:49
【问题描述】:

我在 C# 中使用 RichTextBox。我需要在一个richTextBox 中显示不同长度的字符串,但是这些字符串应该完全对齐.. 这是一个例子..

abcd   abcde  abcde
ab     abc    abcdef

我知道如何使用 setw 函数在 c++ 中执行此操作。但我在 c# 中找不到等效项。

【问题讨论】:

  • String.PadRight(int maxLen)?
  • 谢谢,没想到这么简单!

标签: c# alignment formatting setw


【解决方案1】:
string varName=String.Format("{0,10:D}", 2);

这会将数字 2 格式化为宽度为 10 的字符串,右对齐,使用 -5 使其左对齐,宽度为 5...

来源:http://answers.yahoo.com/question/index?qid=20100727164827AAqJ1Hn

【讨论】:

    【解决方案2】:

    你可以使用String.PadRight

    innerString.PadRight(10);
    

    【讨论】:

      【解决方案3】:

      我为此创建了一个函数:

      public string tab(string s, int w)
      {
          //w is the desired width
          int stringwidth = s.Length;
          int i;
          string resultstring = s;
      
          for(i=0;i<=(w-stringwidth)/8;i++)
          {
              resultstring = resultstring + "\t";
          }
          return resultstring;
       }
      

      然后,将其添加到 ListBox 中,例如:

      listBox.Items.Add(tab("MyFullNameHere",30)+ tab("MyContact - xxxxx",12));
      listBox.Items.Add(tab("MyWifeFullNameHereVeryLong", 30) + tab("HerContact - xxxxx", 12));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-26
        • 2019-07-13
        • 1970-01-01
        相关资源
        最近更新 更多