# Algorithm for Word Wrap

Does anyone know an algorithm to calculate word wrap if you
are given a sentence and a maximum of a line?
i.e. A sentence is 45 characters long, and the max only
allows 40 characters. Therefore if the sentence is 45 chars long then it will wrap the last word around if the last word starts at the 39th character in the sentence.
The only things given are the String and the max_line_lenght. Please let me know if anyone can help.

###### Who is Participating?

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
// I assume for the example that we are printing out to
// the ostream. This example does not handle tabs
// I assume that spaces are the only delimiters
// I also don't handle the case where a word is longer than
// the line length (but these modifications are not impossible)
void wrapLine(ostream &os, const char *p, int length)
{
int charsleft = length;
int size;
const char *pNextWord;

while(*p)
{
pNextWord = strchr(p, ' ');
if(pNextWord == NULL)
{ // at end of line
pNextWord = strchr(p, '\0');
assert(pNextWord != NULL); // must be true!
}
size = pNextWord - p;
// here you should check if the word is longer than the line size
// if so take appropriate action for your app
if(pNextWord - p > charsleft)
{
os << endl; // print endline (wrap)
charsleft = length;
}
else
{
os.write(p, size);
charsleft -= size;
p = pNextWord;
if(*p)
{
if(charsleft)
{
os << *p; // write delimiter
} // otherwise we're going to wrap, eat the space
p++;
}
}
}
}

0

Experts Exchange Solution brought to you by