1

我有一个长字符串要显示到控制台,并希望将字符串拆分为几行,以便它很好地围绕分词符并适合控制台宽度。

例子:

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

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

4

2 回答 2

4

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);
    }
于 2013-03-16T05:00:08.577 回答
1

尝试这个

 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());
于 2013-03-16T04:55:56.700 回答