I am looking for an algorithm that takes a string and breaks it into a certain number of parts. These parts should contain complete words (therefore, spaces are used to separate the line), and the parts should be almost the same length or contain the longest parts.
I know that it is difficult to program a function that can do what I want, but I wonder if there is a well-established and fast algorithm for this purpose?
edit: To clarify my question, I will describe your problem that I am trying to solve.
I generate images with a fixed width. In these images, I write usernames using GD and Freetype in PHP. Since I have a fixed width, I want to split the names into 2 or 3 lines if they do not fit into one.
To fill as much space as possible, I want to split the names so that each line contains as many words as possible. By this I mean that in one line there should be as many words as necessary in order to keep the length of each line next to the average line length of the entire text block. Therefore, if there is one long word and two short words, two short words should stand on the same line if all lines are equal.
(Then I calculate the width of the text block using 1, 2 or 3 lines, and if it fits into my image, I visualize it. Just if there are 3 lines and this does not fit, I reduce the font size until everything is fine. )
Example: This is a long text should display something like this:
This is a long text
or
This is a long text
but not:
This is a long text
and also no:
This is a long text
Hope I can explain what I'm looking for.
ralle source share