std::string wordWrap(std::string sentence, int width=55)
{
//this iterator is used to optimize code; could use array indice
//iterates through sentence till end
std::string::iterator it = sentence.begin();
//this iterator = it when you reach a space; will place a newline here
//if you reach width; also kind of hackish (used instead of comparing to NULL)
std::string::iterator lastSpace = sentence.begin();
int distanceToWidth = 0;
while (it != sentence.end())
{
//TODO: possible to stop recomparing against .end()?
while (it != sentence.end() && distanceToWidth <= width)
{
distanceToWidth++;
if (*it == ' ')
{
lastSpace = it;
//happens if there is a space after the last character
if (width == distanceToWidth)
{
*lastSpace = '\n';
}
}
++it;
}
//happens when lastSpace did encounter a space
//otherwise
if (lastSpace != sentence.begin())
{
*lastSpace = '\n';
}
lastSpace = sentence.begin();
distanceToWidth = 0;
}
return sentence;
}
I am doing a LOT of text printouts using cout<< because it's a text based RPG type...simulation..something game. So there are a lot of areas of text..sometimes in long blocks..sometimes paragraph format and others. Basically I was currently doing a lot of cout as multi-line...and after every few sentences running an endl. So I found this...this works great except I can't do extrapolation (or whatever it's called with it). I just have 3 questions.
1) is this function good/safe....is it going to be ok programatically to use this function or is there something bad with it?
2) Is there anything I can do to improve upon this functio?
3) There is one issue with the function..it works great all the way up until the very end of the wordwrap..the last line always has the last few words cut down on a new line prematurely...very strange.
The TODO on line 14 ... removing the check against .end() will result in crashes as is.
The main problem with the function is that it is about 5x longer than it needs to be.
Also, it does not handle the case where the input sentence already contains line breaks.
You may want to write some other functions to replace newlines in spaces before word wrapping
(since that will throw it off) or make the function cognizant of newlines. Also, you may want to
remove tabs as well, since the function will treat tabs as a single character but they will consume
8 spaces of output.
EDIT: above code does not quite like it when the input text contains words whose lengths are
greater than the specified width. I'll let it up to you to fix that.