C code for reversing senetence keeping words as it is

C program to reverse a sentence keeping the words as it is
#include<stdio.h>
void reverse1(char *x);
void reverse2(char *first, char *last);
int main()
{
char sentence[40];
printf("Enter few string:\n");
gets(sentence);
printf("You Entered:%s\n",sentence);
reverse1(sentence);

return 0;
}
void reverse1(char *s)
{
char *temp=s;
char *word=s;

//temp=s;
//word=s;

while(*temp)
{
temp++;
if(*temp=='\0')//then reverse the word
{
reverse2(word,temp-1);
}
else if(*temp==' ')//then reverse the word
{
reverse2(word,temp-1);
word=temp+1;//word after space becomes the new word
}
}
reverse2(s,temp-1);//then reverse the sentence
printf("Reversed String is:%s\n",s);
}
void reverse2(char *firstt, char *lastt)
{
char t;
while(firstt<lastt)
{
t=*firstt;
*firstt=*lastt;
*lastt=t;
firstt++;
lastt--;
}
}
/*Enter few string:
India is Great
You Entered:India is Great
Reversed String is:Great is India

*/

No comments:

Post a Comment