Sunday, July 12, 2009

Urgent question: How do I reverse strings in C?

Example: I will ask the user to enter a word. Say, he entered, 'Beautiful' The outcome will be: 'lufituaeB'

Urgent question: How do I reverse strings in C?
try this one:





#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt;





rev(char * s),j,i;


char inbuf[20],conv[20],n;





int main()


{


printf("enter a word with max 20 characters : ");


fgets(inbuf, 20, stdin);


rev(inbuf);


printf("the reverse word is %s",inbuf);


}





rev(char * s)


{


j=0;


for (i=21;i%26gt;0;i--)


{


conv[j]=inbuf[i];


j++;


}


return conv;


}
Reply:#include%26lt;string.h%26gt; and then use the function strrev(stringName);


to reverse. Or if you need the logic then above provided solution will work fine..
Reply:void reverse(char *str)


{


int i=strlen(str);


int j=0;


char x;


for(j=0;j%26lt;i/2;j++)


{


x=str[j];


str[j]=str[i-j-1];


str[i-j-1]=x;


}


}

lady palm

No comments:

Post a Comment