justifyText
Write the function justifyText that takes a string (which may be multi-line, or
just one potentially very long line) and a width (which you may assume is
a positive integer), and returns that same text as a multi-line string that is
left- and right- justified to the given line width. For example, consider the
following text:text = """\
We hold these truths to be self-evident: that all men are created equal;
that they are endowed by their Creator with certain unalienable rights;
that among these are life, liberty, and the pursuit of happiness."""
WIth this text, a call to justifyText(text, 30) would return this text left-
and right-justified with 30 characters per line, as such:
"""\
We hold these truths to be
self-evident: that all men are
created equal; that they are
endowed by their Creator with
certain unalienable rights;
that among these are life,
liberty, and the pursuit of
happiness."""
Here are some specifics to keep in mind:
- You should first replace all sequences of any length of whitespace
(spaces, tabs, newlines) with a single space.
- Then, for each line except the last line, find the space as far to the
right as possible while still allowing the line to remain under the given
width restriction. That space will be replaced with a newline ("\n").
- What if a line has no such space, and instead it is solid non-spaces?
This is unlikely, but we still have to deal with it. In this case, just
insert a newline at the given line width. Do not add a hyphen in this case.
- Now, unless the line is a perfect fit in the given width (as in the
second line above ), you will have to add some extra spaces to make it fit
exactly. Consider the first line in the example above ("We hold these
truths to be"). There are 5 total spaces (one between each word), and since
the line is 26 characters long, it requires 4 more spaces to pad out to a
width of 30. This is done by adding an extra space to each space from
left-to-right. In this case the first 4 spaces are now 2 spaces, and the
last space is still one space. This process works in general, so you may
have to add more than one extra space of padding to each gap (such as the 3
total spaces between "certain" and "unalienable"), and there cannot be more
than a 1-space difference between any two gaps on a line, and the extra
spaces must all be on the left side of the line.
- The last row is not justified.