Saturday, May 22, 2010

C-program to reverse a string without using string concepts?

string functions shouldnot be used.

C-program to reverse a string without using string concepts?
first set up a counter to find the string length.


find the character at the last position and print it


decrement the counter and go on printing successive characters


if you need, store it in another array and then print it at the same time
Reply:void reverse(char *s)


{


int i, j, l;


char c;


for(i=0,l=0;*s!='\0';i++,l++);


for(i=0, j=l;i%26lt;=j;i++,j--)


{


c=*(s+i);


*(s+i)=*(s+j);


*(s+j)=c;


}


}








Or








By Using a Stack also we can do it.


i.e. first push all the char's in the string to the stack


and then pop each char at a time and print them.


That gives the reverse of the string .
Reply:void reverse(char s[]) {


int i, j;


char c;





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


c = s[i];


s[i] = s [j];


s[j] = c;


}


}


No comments:

Post a Comment