I have been trying to reverse the order of a sentence containing a string using pointers. My code snippet:
int main()
{
char c[50];
char *ptr;
int i=0,len;
gets(c);
ptr=c;
len=strlen(c);
for(i=len-1;i>=0;i--)
printf("%c",*(ptr+i));
return 0;
}
This code generates a reverse of the string I enter correctly. Like for example:
Input: how are you
output: uoy era woh
But what I kept in mind was entirely different, I just wanted the order of the words in the sentence to reverse and not the exact words to reverse. For example, for the same input "how are you" I want the output to be "you are how". Ive been breaking my head for quite some time now. Is there something that Im missing???
Re-EDIT: I want to do the reverse concept using pointers and pointers only!!! thats why i posted as a new question!!!
As suggested by another user, I tried using the strtok() function too and my output works kinda fine but is throwing garbage values.... Kindly help to this context::
#include <stdio.h>
#include <stdlib.h>
int main()
{
char c[50],d[50];
char *ptr,*aptr,*tok;
int i=0,j=0,len;
gets(c);
ptr=c;
aptr=d;
len=strlen(c);
printf("%d\n",len);
for(i=len-1;i>=0;i--,j++)
*(aptr+j)=(*(ptr+i));
for(i=0;i<len;i++)
printf("%c",d[i]);
printf("\n");
tok=strtok(aptr," ");
while(tok!=NULL)
{
printf("%s\n",strrev(tok));
tok=strtok(NULL,aptr);
}
return 0;
}
and i Finally landed at the most optimized answer!!!!
#include <stdlib.h>
int main()
{
char s[20][20];
int i=0,length=-1;
for(i=0;;i++)
{
scanf("%s",s[i]);
length++;
if(getchar()=='\n')
break;
}
for(i=length;i>=0;i--)
printf("%s ",s[i]);
return 0;
}