Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / string

Simple Word Wrapping in C#

4.50/5 (8 votes)
16 Jun 2020MIT 26K   959  
Easily word wrap strings of text in C#
This is just a quick and dirty way to word wrap strings to a specified column width.

Introduction

This is just a little extension method you can use to word wrap text to a specified column width.

Coding this Mess

Using this is pretty simple. You just call the WordWrap() extension method and pass it the column width you'd like.

C#
using System;
using WW;
namespace WordWrapDemo
{
    class Program
    {
        static void Main()
        {
            var text = "The quick brown fox jumped over the lazy dog";
            Console.WriteLine(text.WordWrap(10));
        }
    }
}

This will word wrap the text clamping to 10 characters in width.

Limitations

  • If you have a single word that is greater than the specified column width, it will overrun the column boundary to the right. This is the only case where your text might "spill over" beyond the width specified. This is by design. There's no great way to handle it. The other options would have been to truncate the word, or to hard break the word in the middle of it somewhere.
  • Unfortunately, this does not preserve whitespace, except line breaks. Tabs will be converted to spaces and multiple characters of whitespace will be turned into a single space. Making this preserve whitespace greatly increases the complexity so I decided not to do it.

History

  • 16th June, 2020 - Initial submission

License

This article, along with any associated source code and files, is licensed under The MIT License