PDA

View Full Version : QStrung::replace problem



high_flyer
7th September 2006, 12:38
Hi,
I am trying to replace some parts of a string, and for some reason, it works very strange so I was hoping someone here could point out what it is I am doing wrong...
I am reading lines out of a text file, and in each line I am sarching for ';' and replacing them with "###".
But I don't want to replace all ';'s just some that apear in certain places.
Here is the code:


//text contains the current read line
//count 9 ';' and replace the 10th with "### "
for(int i=0; i<10 && pos!=-1; ++i)
{
if(pos !=-1)
{
pos++;
pos = text.indexOf(";",pos);
}
}
qDebug()<<"pos:"<<pos;
if(pos !=-1)
text.replace(pos,"###")
qDebug()<<text;



The debug output is half correct, which is the strange part.
The pos value is correct, that is, the position in the string is the correct position of the ';' that should be replaced, but the second debug, which returns the string after the change is with out any change in the string.
The next strings are being changed, but with no corelation to where they should...

Any help is very appreciated.
Thanks.

EDIT:
I found my error - I forgot a parameter the replace method.

danadam
7th September 2006, 13:11
for (int i=0; i<10 && pos!=-1; ++i)
{
if (pos !=-1)
{
pos++;
pos = text.indexOf(";",pos);
}
}

This if statement is unnecessary. If you entered the loop body, than pos != -1 is always true, because it's in loop condiiton.


EDIT:
I found my error - I forgot a parameter the replace method.
Yes, I noticed. There is no replace() method with only 2 parameters according to QT documentation. Didn't compiler give you any errors or warnings?

windkracht8
11th September 2006, 13:30
And how about?


for (int i=0; i<10 && pos!=-1; ++i) pos = text.indexOf(";",++pos);