There is a line: Quisque velit nisi, pretium ut lacinia in, elementum id enim. Nulla porttitor accumsan tincidunt. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Nulla porttitor accumsan tincidunt.
It is necessary to break it into three parts, but save whole words and move it to the next line only after the end of the word. For example, we break into three lines:
Quisque velit nisi, pretium ut lacinia in, elementum id enim. Nulla porttitor accumsan tincidunt. Now I use this simple code, but it cuts whole words:
int chunkSize = string.Length / 3; int stringLength = string.Length; for (int i = 0; i < stringLength; i += chunkSize) { if (i + chunkSize > stringLength) chunkSize = stringLength - i; Console.WriteLine(string.Substring(i, chunkSize)); } It turns out at the output:
Quisque velit nisi, pretium ut l acinia in, elementum id enim. Nu lla porttitor accumsan tincidunt . Tell me how can this be easier to implement?
UPDATE
Important: the original string may differ from the above. May contain any characters.
Found a simple solution here https://stackoverflow.com/a/17571171/2127124
public static class ExtensionMethods { public static string[] Wrap(this string text, int max) { var charCount = 0; var lines = text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); return lines.GroupBy(w => (charCount += (((charCount % max) + w.Length + 1 >= max) ? max - (charCount % max) : 0) + w.Length + 1) / max) .Select(g => string.Join(" ", g.ToArray())) .ToArray(); } }
' ') and it needs to be divided into K parts, then the number of possible partitions is(N - K + 2) * (N - K + 1) / 2provided thatN >= K. What partition of these will suit you? Anyone? Or do you need the most optimal (with the lengths of the pieces closest tostr.Length / K)? - Andrei NOP