Thursday, July 30, 2009

How to reverse a string using C???

FOR EXAMPLE:


Ram shyam output should be "maR mayhs"

How to reverse a string using C???
I think u phrased ur question wrong buddy .. from the example u have given it seems u want to reverse string word by word rather then complete string in one go ..


In that case use the following method


scan the string for space


for each block use the programs as suggested by other answers ..


cheers


sachin
Reply:#include %26lt;stdio.h%26gt;


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


#define SWAP_CHAR( x, y ) {char c; c = x; x = y; y = c;}


#define MAX 81


void reverse(char []);





void main(void)


{


char text[MAX];





printf("Enter a character string.\n");


gets(text);


reverse(text);


puts(text);


}





void reverse(char t[])


{


int i,j;


for(i = 0, j = strlen(t)-1; i %26lt; j; i++, j--)


SWAP_CHAR(t[i], t[j]);


}
Reply:main()


{


char a[] = "Ram shyam";


int n = strlen(a)-1;


int i;





printf("%s\n\n",a);


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


{


char c = a[i];


a[i] = a[n-i];


a[n-i]= c;


}





printf("%s\n\n",a);


}


No comments:

Post a Comment