My experience is more general architecture and software design not code snippets like this. See any improvement to my code?
var message = @"This is a test message
012345678901234567890123";
var output = Split(message, 20);
output
"This is a test",
"message",
"01234567890123456789",
"0123"
Max length of a line is 20 chars and it does not split words if not needed
code:
private IEnumerable<string> Split(string text, int maxLength)
{
var n = '\n';
var whiteSpaces = new HashSet<char> { ' ', '\t', n };
text = text.Replace(Environment.NewLine, n.ToString());
if (!text.EndsWith(n)) text += n;
var whiteSpaceIndices = text
.Select((c, i) => (i, c))
.Where(t => whiteSpaces.Contains(t.c))
.ToList();
var index = 0;
var line = string.Empty;
char? last = null;
foreach (var white in whiteSpaceIndices)
{
do
{
var wordLength = white.i - index;
var wordTrimmed = text.Substring(index, Math.Min(maxLength, wordLength));
var wordWasTrimmed = wordLength > maxLength;
var trimmedTotalLength = wordTrimmed.Length + (wordWasTrimmed ? 0 : 1);
if (line.Length + trimmedTotalLength > maxLength || last == n)
{
if (line != string.Empty)
yield return line;
last = null;
line = string.Empty;
}
line += last;
line += wordTrimmed;
index += trimmedTotalLength;
} while (index < white.i);
last = white.c;
}
if (line != string.Empty)
yield return line;
}
https://dotnetfiddle.net/gpT5UY
Target framework is Core 3.1
maxLength
characters if there are no whitespace characters to split on? (so an individual word with more thanmaxLength
characters) or should these words be split and an optional hyphen or continuation character/string be injected? \$\endgroup\$ – Chris Schaller Sep 28 '20 at 3:02