Editor

Word Wrap

#312 · Strings · Intermediate · 70 XP · about 14 min

Write wrap(text, width) that breaks text into lines no longer than width characters and returns the lines as a list of strings.

  • Words are the runs of characters that are not whitespace. A word is never split.
  • Fill each line greedily: put the next word on the current line, after one space, if the line stays within width; otherwise start a new line with it.
  • A word longer than width goes on a line of its own.
  • Paragraphs are separated by blank lines (lines that are empty or hold only spaces). Wrap each paragraph separately and put an empty string between two paragraphs in the result. Inside a paragraph, single line breaks and runs of spaces count as one space.
  • Paragraphs with no words are left out, so text with no words gives an empty list.

Examples

wrap('The quick brown fox jumps over the lazy dog', 10)
# returns ['The quick', 'brown fox', 'jumps over', 'the lazy', 'dog']
wrap('a supercalifragilistic word', 8)
# returns ['a', 'supercalifragilistic', 'word']
wrap('One two three.\n\nFour five.', 9)
# returns ['One two', 'three.', '', 'Four', 'five.']

Constraints

  • 1 <= width <= 200
  • text has at most 100,000 characters, and its only whitespace characters are spaces and \n.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.