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