Post History
Sandbox
Word wrap a string
#1: Initial revision
Word wrap a string
Given a string `s` of text and a line length `l`, your task is to word-wrap that text to that line length. Concretely, the given string consists of words separated by single spaces, with no leading or trailing space. The task is then to replace spaces by newlines such that in each line, there are no more than `l` characters, but including the next word (that is, sequence of non-space characters) would have caused to exceed that limit. If a word is longer than the specified line length, it must occupy a line by itself. This is code golf, the shortest code wins. Testcases: Each test case has the string as first line, the line length as second line, and the result as remaining lines. ```text The quick brown fox jumps over the lazy dog. 10 The quick brown fox jumps over the lazy dog. ``` ```text Break different topics up into paragraphs. 8 Break different topics up into paragraphs. ``` ```text Just one line! 20 Just one line! ```