Wednesday, March 4, 2009

Word Wrap Code

This is a code to wrap a QString if it exceeds a particular number of characters per line, without splitting any word into different lines.

Signature : QString wordWrap(const QString &str, int wrapLength)
Argument : 1. The QString to be wrapped
2. The permissible number of characters per line.

Return Value: The wrapped QString

QString wordWrap(const QString &str, int wrapLength)
{
QString tempStr= str;
int len = str.length(), pos= (wrapLength>1)?wrapLength -1:1;

while(pos < len-1){

int tempPos=pos;
while(tempStr.at(tempPos)!=' ' && tempPos > 0){

tempPos--;
}
if(tempPos > 0)pos=tempPos;

tempStr.replace(pos,1,'\n');
pos+=pos;
}

return tempStr;
}

3 comments:

Samrat Roy said...

Good stuff! But I would ask you to use code printing formatting to make the code more readble.

Ali said...

hello everybody,
Good code, but it not work very well, I have try some string and I got some prolem.
below I post a correcte version of "The wrapped QString" code... ;)

QString wordWrap(const QString &str, int wrapLength, int &countLine)
{
QString tempStr= str;
int len = str.length();
int pos = (wrapLength > len-1) ? len-1 : wrapLength;

while(pos < len-1) {
int tempPos = pos;
while(tempStr.at(tempPos) != ' ' && tempPos > 0)
tempPos--;
tempStr.replace(tempPos,1,'\n');
countLine++;
pos += tempPos;
}
return tempStr;
}

Unknown said...

QString wordWrap(const QString &str, int wrapLength)
{

QString tempStr= str;
int len = str.length();
int pos = (wrapLength > len-1) ? len-1 : wrapLength;
int width=pos;
int temp =pos;

while(pos < len-1) {

int tempPos = pos;


while(tempStr.at(tempPos) != ' ' && tempPos > 0) {
tempPos--;
temp--;
}

tempStr.replace(tempPos,1,'\n');

pos += temp;
temp=width;



}
return tempStr;
}

Post a Comment