to Reverse the words in the string... help.. I just can't see the error...
I want to make a string to reverse the words but remain the words position the same.. (if input is "Hello world haha", the output should be "olleH dlrow ahah"), what should I do.. can I use the recursive method.. but how.. here is what I have done...
Code:
#include <stdio.h>
void revstr (char str[]);
main()
{
char str[100];
printf ("Enter the String :");
gets (str);
revstr (str);
return 0;
}
void revstr (char str[])
{
int i=0, j, k;
char word[50], reverse[50];
for (i=0; str[i]!='\0'; i++)
{
while (str[i]!=' ')
{
word[i]= str[i];
word[i+1]='\0';
}
for (j=i, k=0; (j>=0) || (str[j]=' '); j--, k++)
{
reverse[k] = word[j];
word[j] = '\0';
reverse[k+1] = ' ';
reverse[k+2] = '\0';
}
puts (reverse);
}
}
What I did is to iniciate word array to store words reverse array to reverse the letters, and put out the reverse array string by string.. it seem to be the stupidest way to do so...
Question... Help... and Desperation.....
Thanks for Prelude's reply really appricate a lot.. however, when I try to impliment into my programe with the functions, it have general protection exception error. :( and the programme halt. I don't understand what's went wrong. Could it be the problem of the string being pass down from the main program ?
Here is the whole programe.
Code:
#include <stdio.h>
#include <ctype.h>
#incldue <string.h>
int revstr (char str[]);
static void reverse ( char *start, char *end );
main()
{
char str[100];
printf ("Enter the String :");
gets (str);
revstr (str);
return 0;
}
int revstr (char str[])
{
char *last = str + sizeof str;
char *start = str;
char *end;
for ( end = start; end != last; start = ++end ){
while ( *end != '\0' && !isspace ( *end ) )
end++;
reverse ( start, end - 1 );
}
printf ( "%s\n", str );
return 0;
}
static void reverse ( char *start, char *end )
{
char hold;
while ( start < end ) {
hold = *start;
*start = *end;
*end = hold;
start++;
end--;
}
}
Is there anything I can do with the programe. And what should I do to able to achieve the C programming skill like you. (I have seen the other reply you have pose... SUPERB!!!!) Any tips... :D