This should work, although it can probably be reduced further:
public static void WordWrap(string paragraph) { paragraph = new Regex(@" {2,}").Replace(paragraph.Trim(), @" "); var left = Console.CursorLeft; var top = Console.CursorTop; var lines = new List<string>(); for (var i = 0; paragraph.Length > 0; i++) { lines.Add(paragraph.Substring(0, Math.Min(Console.WindowWidth, paragraph.Length))); var length = lines[i].LastIndexOf(" ", StringComparison.Ordinal); if (length > 0) lines[i] = lines[i].Remove(length); paragraph = paragraph.Substring(Math.Min(lines[i].Length + 1, paragraph.Length)); Console.SetCursorPosition(left, top + i); Console.WriteLine(lines[i]); } }
This can be hard to understand, so basically what it does:
Trim() removes spaces at the beginning and end.
Regex() replaces multiple spaces with a single space. The for loop takes the first (Console.WindowWidth - 1) character from the paragraph and sets it as a new line.
`LastIndexOf () 1 tries to find the last space in the string. If he is not there, he leaves the line as it is.
This line is removed from the paragraph and the loop repeats.
Note. The regular expression was taken from here . Note 2: I do not think it replaces tabs.
source share