Search code examples
c#stringword-wrap

How can I format a C# string to wrap to fit a particular column width?


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?


Solution

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