Please review the following code and compare with yours. Take note of the comments and try to understand why I made the changes that I made. I tried to keep the spirit of the algorithm the same, even though I'd probably do this differently:
#include<stdio.h>
#include<string.h>
int main(void)
{
char s[] = "I Am Sad";
char str[10] = ""; /* Make sure to initialize str because its length is taken shortly */
int i = 0;
char *st2;
char *st;
st = &s[0];
while (*st != '\0') {
if (*st == ' ')
st2 = st;
*st++;
}
for (; strlen(str) < strlen(s);) {
/* What if st2 == s? */
if (*st2 == ' ')
++st2;
st = st2;
/* Don't reset i if you want to append to str */
while (*st != '\0' && *st != ' ')
str[i++] = *st++;
str[i++] = ' ';
/* Don't forget to skip whitespace or you'll always process the same word */
while (st2 != s && *--st2 == ' ')
;
/* Now find the previous word. Don't forget to check for the start of the string */
while (st2 != s && *st2 != ' ')
--st2;
}
str[i] = '\0';
puts(str);
return 0;
}