1

I have a long string I'd like to display to the console and would like to split the string into several lines so that it wraps nicely along word breaks and fits the console width.

Example:

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

What is the best way to achieve this?

kkahl
  • 415
  • 5
  • 17
  • Refer [System.Console](http://msdn.microsoft.com/en-us/library/system.console.aspx) class it has verious methods which could help you in achieving it – Krishnaswamy Subramanian Mar 16 '13 at 05:00
  • @KrishnaswamySubramanian I went through the System.Console documentation and did not see any methods that would handle the case that were stated in this question. If there indeed is one, would you care to point out the one you had in mind? There were many variations of the Console.WriteLine method, but I didn't see any that handle word wrapping. – Unome Jun 08 '15 at 15:22

2 Answers2

4

Bryan Reynolds has posted an excellent helper method here (via WayBackMachine).

To use:

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

An enhancement to use the newer C# extension method syntax:

Edit Bryan's code so that instead of:

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

It reads:

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

Then use like this:

    foreach(String s in e.Message.Wrap(Console.Out.BufferWidth))
    {
        Console.WriteLine(s);
    }
kkahl
  • 415
  • 5
  • 17
  • Nice code, wish it was posted without the linenumbers... – EricRRichards May 30 '15 at 20:01
  • 1
    Fantastic solution, the extension is simple, elegant, and works like a charm. +1 – Unome Jun 08 '15 at 15:17
  • 1
    This suffers from link rot and now the actual code that would have been useful cannot be found. :-( – Norman H Mar 22 '17 at 21:07
  • 1
    Thanks for reporting the broken link, @NormanH. I was able to repair the link by pointing it to the archived content in the Internet Archive WayBackMachine. – kkahl May 27 '17 at 09:04
1

Try this

 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());
internals-in
  • 4,798
  • 2
  • 21
  • 38