Friday, April 8, 2011

#C_CODE: Reverse String

#include <stdio.h>
#include <string.h>
 
void reverse(char *s)
{
 int len = strlen(s)-1;
 int i;
 for(i=0; i < strlen(s)/2; i++)
 {
  s[i]   ^= s[len];
  s[len] ^= s[i];
  s[i]   ^= s[len--];
 }
}

int main(void)
{
 char buff[35];
 fputs("Input string: ",stdout);
 fgets(buff,sizeof(buff),stdin);
 fflush(stdin);
 *(buff + strlen(buff) -1 ) = '\0';

 reverse(buff);
 printf("\n The reversed string is: %s\n",buff);
 getchar();
}

REF: C Programming Language-K&R

No comments: