I was practicing some programming problems and tried to code the popular “reverse words in a string” problem.
I tried to come up with my own code in C. I am able to partially get it right. That is, “hello world” becomes “world olleh”. I am wondering what the bug is here. I think somewhere I am creating an off by 1 bug.
As much as possible, I wanted to do it without using library functions. I searched here for this problem & found many solutions, but I’d like to know why my solution doesn’t work.
Here is the code:
#include <stdio.h>
#include <string.h>
void reverse(char*, int);
int main(int argc, char **argv)
{
char st[]= "hello world";
int len = strlen(st);
int i=0,j=0;
reverse(st,len-1); // Reverse the entire string. hello world => dlrow olleh
while(st[j]){ //Loop till end of the string
if ( *(st+j) == ' ' || *(st+j) == '\0' ) { //if you hit a blank space or the end of the string
reverse(st+i,j-1); // reverse the string starting at position i till position before the blank space i.e j-1
i=++j; //new i & j are 1 position to the right of old j
}
else {
j++; //if a chacacter is found, move to next position
}
}
printf("%s",st);
return 0;
}
void reverse(char *s, int n)
{
char *end = s+n; //end is a pointer to an address which is n addresses from the starting address
char tmp;
while (end>s) //perform swap
{
tmp = *end;
*end = *s;
*s = tmp;
end--;
s++;
}
}
Thank you!
UPDATE: Based on @Daniel Fischer’s answer, here is the correct implementation : http://ideone.com/TYw1k
The problem is that
the
whilecondition prevents the loop being entered at the end of the string, so the last word doesn’t get reversed again.You can either make it an infinite loop, and add an
after the reversing, or reverse the last word after the while loop was left.