views:

77

answers:

1
+2  Q: 

split line of text

Hi all,

I was wondering if there is an algorithm to split a line into multiple lines, so that the resulting set of multiple lines fit into a squared shape rather than a wide rectangular shape. Let me give some examples,

Input: Hi this is a really long line.

Output:
Hi this is
a really
long line

Input: a b c d e f

Output:
a b c
d e f

Input: This is really such looooooooooooooooooooong line.This is the end.

Output:
This is really such
looooooooooooooooooooong
line This is the end.

If you see in the above examples, input line fits into a wide rectangle. But the output more or less fits into a squared shape.

Essentially what needs to be done here is simply count the number of characters in the line, take the square root of that number. Then put square root number of characters in each line. But in the above example, the splitting needs to be done by respecting word wraps instead of characters. Is there any standard algorithm for this? Any code examples/ pointers would be appreciated!

+1  A: 

As you have observed, this basically means breaking lines with a minimum and maximum width, as opposed to just a maximum width, which is what is usually done. (And your example shows that it isn't always possible if you can't hyphenate words.) TeX can do this (look at the \parshape command): its line-breaking algorithm supports arbitrary shapes (and hyphenation, too), and is considered the state of the art. So if you want to create squares in any serious way, you should definitely adapt the Knuth/Plass algorithm (http://defoe.sourceforge.net/folio/knuth-plass.html).

Kilian Foth