Update 7/11/2016 Updated Code To use Linq

This code string extension which will take a specific max line size and fit only words into those lines.

For example if one split on this sentence: “The Fall River” would make three strings of “The “, “Fall “ and “River”.

I have placed this into a string extension which could be called such as

List<string> items = "The Fall River".SplitOn( 5 );

Here is the extension method

// using System.Text.RegularExpressions;
public static class StringExtensions
{

    /// <summary>Use this function like string.Split but instead of a character to split on, 
    /// use a maximum line width size. This is similar to a Word Wrap where no words will be split.</summary>
    /// Note if the a word is longer than the maxcharactes it will be trimmed from the start.
    /// <param name="initial">The string to parse.</param>
    /// <param name="MaxCharacters">The maximum size.</param>
    /// <remarks>This function will remove some white space at the end of a line, but allow for a blank line.</remarks>
    /// 
    /// <returns>An array of strings.</returns>
    public static List<string> SplitOn( this string initial, int MaxCharacters )
    {

        List<string> lines = new List<string>();

        if ( string.IsNullOrEmpty( initial ) == false )
        {
            string targetGroup = "Line";
            string pattern = string.Format( @"(?<{0}>.{{1,{1}}})(?:\W|$)", targetGroup, MaxCharacters );

            lines = Regex.Matches(initial, pattern, RegexOptions.Multiline | RegexOptions.CultureInvariant )
                         .OfType<Match>()
                         .Select(mt => mt.Groups[targetGroup].Value)
                         .ToList();          
        }
        return lines;
    }
}

Here is an example with output of its usage:

string text = "The rain in spain falls mainly on the plain of Jabberwocky falls.";

List<string> lines = text.SplitOn( 20 );

foreach ( string line in lines )
    Console.WriteLine( line );

/*
The rain in spain
falls mainly on the
plain of Jabberwocky
falls.
 */

foreach ( string line in text.SplitOn( 11 ) )
    Console.WriteLine( line );

/*
The rain in
spain falls
mainly on
the plain
of
Jabberwocky
falls.
 */
Share