>And it does work.
No, it doesn't. This could be because of your hackish solution as you say, but with the input "they call me jim", the output not only fails to be "jim me call they", it also fails to be a perfect reversal of the original string (with or without spaces). Try passing length as a reference parameter to word and update it in both loops. That would give you better results:
Code:
char * word( char * s, int * l )
{
int x = 0;
static char buf[BUFSIZ] = {0};
memset( buf, 0, BUFSIZ );
while( s && *s && isspace( *s ) ) s++, (*l)++;
while( s && *s && !isspace( *s ) && x < BUFSIZ-1 ) buf[x++] = *s++, (*l)++;
return buf;
}
void revword( char * s )
{
if( s && *s )
{
revword( s+1 );
putchar( *s );
}
}
int main( void )
{
char *foo = "they call me jim";
char *bar = foo;
int length = 0;
do
{
bar = word( foo + length, &length );
revword( bar );
putchar( bar[0] == '\0' ? '\n' : ' ' );
} while( bar && *bar );
return 0;
}
Or you could forgo recursion entirely and go with an in-place solution.
Code:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
void reverse ( char *s, int len )
{
int i, j;
for ( i = 0, j = len - 1; i < j; i++, j-- ) {
char save = s[i];
s[i] = s[j];
s[j] = save;
}
}
void revword ( char *s )
{
while ( *s != '\0' ) {
char *e = s;
/* Find the end of a word */
while ( *e != '\0' && !isspace ( *e ) )
e++;
reverse ( s, e - s );
/* Find the next word */
s = e;
while ( *s != '\0' && isspace ( *s ) )
s++;
}
}
int main ( void )
{
char s[] = "they call me jim";
reverse ( s, strlen ( s ) );
revword ( s );
puts ( s );
return 0;
}