如何格式化c#字符串以适应特定的列宽度?

本文关键字:格式化 字符串 | 更新日期: 2023-09-27 18:04:16

我有一个很长的字符串,我想要显示到控制台,并希望将字符串分成几行,这样它就可以很好地沿断行换行,并适合控制台的宽度。

的例子:

  try
  {
      ...
  }
  catch (Exception e)
  {
      // I'd like the output to wrap at Console.BufferWidth
      Console.WriteLine(e.Message);
  }

实现这一目标的最佳方法是什么?

如何格式化c#字符串以适应特定的列宽度?

Bryan Reynolds在这里发布了一个很好的辅助方法(通过WayBackMachine)。

使用:

  try
  {
      ...
  }
  catch (Exception e)
  {
      foreach(String s in StringExtension.Wrap(e.Message, Console.Out.BufferWidth))
      {
          Console.WriteLine(s);
      }
  }

使用新的c#扩展方法语法的增强:

编辑Bryan的代码,使其不再是:

public class StringExtension
{
    public static List<String> Wrap(string text, int maxLength)
    ...

:

public static class StringExtension 
{
    public static List<String> Wrap(this string text, int maxLength)
    ...

然后像这样使用:

    foreach(String s in e.Message.Wrap(Console.Out.BufferWidth))
    {
        Console.WriteLine(s);
    }

试试这个

 int columnWidth= 8;
    string sentence = "How can I format a C# string to wrap to fit a particular column width?";
    string[] words = sentence.Split(' ');
StringBuilder newSentence = new StringBuilder();

string line = "";
foreach (string word in words)
{
    if ((line + word).Length > columnWidth)
    {
        newSentence.AppendLine(line);
        line = "";
    }
    line += string.Format("{0} ", word);
}
if (line.Length > 0)
    newSentence.AppendLine(line);
Console.WriteLine(newSentence.ToString());