Is the first line of the following expression:
??Code:while((*(str + i) = *(str + j++)) != \0) { //code here } Equivalent to saying: if (*(str + j) != ) *(str + i) = *(str + j++);
It would really help me to know if it is so.
Is the first line of the following expression:
??Code:while((*(str + i) = *(str + j++)) != \0) { //code here } Equivalent to saying: if (*(str + j) != ) *(str + i) = *(str + j++);
It would really help me to know if it is so.
No. Even if you changed the '\0' to ' ' (or, I suppose, ' ' to '\0'), the first increments j and does the assignment statement no matter what, where the second checks first and then assigns.
What I don't understand is how this loop (the while one) is capable of eliminating spaces in a string with this code:
I know that the condition in this loop is supposed to copy the string by moving the character at position j to the character at position i and then increments j to the next character. If the character copied was \0, you have reached the end of the string and that's it; but I still don't get the ((*(str + i) = *(str + j++)) != \0) part and why it works. I don't how it actually copies the value in the whiel statement since, as you said it, the assignment occurs no matter what. I am confused.Code:// Function to eliminate spaces from a string void eatspaces(char* str) { int i = 0; // Copy to index to string int j = 0; // Copy from index to string while((*(str + i) = *(str + j++)) != \0) // Loop while character is not \0 if(*(str + i) != ) // Increment i as long as i++; // character is not a space return; }
Well, you have to actually read it. The character at str[j] is copied to str[i], and j is incremented (this is what gets us through the string). If it wasn't \0, go through the loop -- and the loop ONLY increments i if the character str[i] is not a space.
Yep, Both looks similar!
I've got it now tabstop. Feel like an idiot now. I read it but it got me confused for some reason. Thanks a lot!
Look at this,
It works in this way,Code:J =1; if ((i=j++)==1) printf("If i-%d,j-%d\n",i,j); else printf("Else i-%d,j-%d\n",i,j);
How different is this from the above eogoldseed's example....?1. i=j
2. if (j == 1) results true
3. then increments the J to 2.
leogoldseed's example removes spaces from a string and yours does not. And J would only be 1 once...whereas in a string there might be several spaces... so even as a demonstration it's quite wrong.
Doing a similar thing with numbers might look like
Code:#include <stddef.h> #include <string.h> int * removeif (int * to, int * from, size_t nelem, int value); int main () { int foo[] = { 1, 2, 3, 4, 3, 2, 1, 1, 2 }; int bar[10]; memset(bar, 0, 10 * sizeof bar[0]); removeif(bar, foo, sizeof foo / sizeof foo[0], 1); return 0; } int * removeif (int * to, int * from, size_t nelem, int value) { size_t i, j; for (i = 0, j = 0; i < nelem; i++) { if (value != from[i]) to[j++] = from[i]; } return to; }