This code should help you. It will check the length of the current line. If in this case it is larger than your maxLength (150), it will start with the 150th character and (in reverse order) find the first non-word character (as described by OP, this is a sequence of non-spatial characters), then it will save the line before that character and starts over with the remaining line, repeating until we finish with a substring that is less than maxLength characters. Finally, join them all together again in the final row.
string line = "This is a really long run-on sentence that should go for longer than 150 characters and will need to be split into two lines, but only at a word boundary."; int maxLength = 150; string delimiter = "\r\n"; List<string> lines = new List<string>(); // As long as we still have more than 'maxLength' characters, keep splitting while (line.Length > maxLength) { // Starting at this character and going backwards, if the character // is not part of a word or number, insert a newline here. for (int charIndex = (maxLength); charIndex > 0; charIndex--) { if (char.IsWhiteSpace(line[charIndex])) { // Split the line after this character // and continue on with the remainder lines.Add(line.Substring(0, charIndex+1)); line = line.Substring(charIndex+1); break; } } } lines.Add(line); // Join the list back together with delimiter ("\r\n") between each line string final = string.Join(delimiter , lines); // Check the results Console.WriteLine(final);
Note. . If you run this code in a console application, you can change "maxLength" to a lower number so that the console does not wrap you.
Note: This code does not enforce any tab characters. If tabs are also included, your situation becomes a little more complicated.
Update: I fixed a bug in which new lines began with a space.
Jon senchyna
source share