Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Sandbox

Post History

60%
+1 −0
Sandbox Word wrap a string

posted 3y ago by celtschk‭

Article code-golf string
#1: Initial revision by user avatar celtschk‭ · 2022-02-02T15:14:58Z (almost 3 years ago)
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!
```