Help with while statement

Hi all,

When I was writing a function to replace all occurrences of %20 with a space I used the following code which only replaced the first occurrence.

while (tmpPos = StringToStrip.indexOf("%20") != -1)
StringToStrip = StringToStrip.substring(0, tmpPos) + " " + StringToStrip.substring(tmpPos + 3);

I modified it to this, which worked:

tmpPos = StringToStrip.indexOf("%20");
while ( tmpPos != -1)
{
StringToStrip = StringToStrip.substring(0, tmpPos) + " " + StringToStrip.substring(tmpPos + 3);
tmpPos = StringToStrip.indexOf("%20");
}

I have since realised I can use the replace method of the String class and done it that way. But I am interested as to why the first bit of code didn't work.

Cheers
Z

didn't work

The "!=" inequality operator has higher precedence than the "=" assignment operator. See Footnote.

So, look at your first statement.

 while (tmpPos = StringToStrip.indexOf("%20") != -1)

This checks to see whether StringToStrip.indexof("%20") is not equal to -1. If it is not equal to -1, tempPos is assigned the value 1. If it is equal to -1 (not not equal), tempPos is assigned the value 0.

If the result, tempPos, is zero, the while stuff will not be executed. If the result, tempPos, is not equal to zero, the while stuff will be executed. At any rate, tempPos does not have the value returned by the StringToStrip() function.

I think what you have in mind would be accomplished by

 while ([glow]([/glow]tmpPos = StringToStrip.indexOf("%20")[glow])[/glow] != -1)

The parentheses around the assignment make sure the assignment is made before testing to see if the result is -1.

Regards,

Dave

Footnote:

If you don't have a book handy, you can check places like http://www.cplusplus.com/doc/tutorial/operators/ Scroll down to "Precedence of operators"

Better yet, maybe, get into a habit of using parentheses to make sure the intent is as clear to a human reader as it is to the compiler. I mean, the compiler never gets confused, but...

Thanks for clearing that up. It's an awfully long time since I did any C or CPP coding but I should have thought of that!

Cheers

Z