Sunday, May 28, 2017

String to multi-lines of max length

Every couple of years I have to split a long string of text into multiple lines of a maximum length. In the latest example I wanted to display long paragraphs of /? help text in a command line utility where each line must be 79 characters maximum length.

I found some of my old code from 14 years ago where I used a complicated loop to split strings, but now it was time to find a better way. I suspected Regex could be used, but I wasn't sure which syntax to use. After lots of tedious web searching I finally found someone who suggested something like the following, which I've tweaked slightly.

string s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin ..."; (cut)
int maxlen = 60;
MatchCollection mc = Regex.Matches(s, @"(.{1," + (maxlen - 1) + @"})(?:\s|$)");
var lines = mc.Cast<Match>().Select(m => m.Value);
lines.Select(x => new { Len = x.Length, Line = x }).Dump();

The last line dumps the resulting split lines and their lengths in LINQPad like this:


Note though that if any words exceed the maximum split line length then they will be truncated.

No comments:

Post a Comment