I have a long string, and I want to put it in a small field. To achieve this, I break the line into lines by spaces. The algorithm is as follows:
public static string BreakLine(string text, int maxCharsInLine) { int charsInLine = 0; StringBuilder builder = new StringBuilder(); for (int i = 0; i < text.Length; i++) { char c = text[i]; builder.Append(c); charsInLine++; if (charsInLine >= maxCharsInLine && char.IsWhiteSpace(c)) { builder.AppendLine(); charsInLine = 0; } } return builder.ToString(); }
But it breaks when there is a short word, followed by a longer word. "foo howcomputerwork" with a maximum length of 16 will not break, but I want this. I thought I had the prospect of seeing where the next gap occurs, but I'm not sure if this will lead to the fewest possible lines.
John NoCookies
source share