Sunday 8 July 2012

Reverse string

C programming code

/* String reverse in c*/
#include<stdio.h>
#include<string.h>
 
main()
{
   char arr[100];
 
   printf("Enter a string to reverse\n");
   gets(arr);
 
   strrev(arr);
 
   printf("Reverse of entered string is \n%s\n",arr);
 
   return 0;
}
/* Second method */

C program to reverse a string using pointers

: Now we will invert string using pointers or without using library function strrev.
#include<stdio.h>
 
int string_length(char*);
void reverse(char*);
 
main() 
{
   char string[100];
 
   printf("Enter a string\n");
   gets(string);
 
   reverse(string);
 
   printf("Reverse of entered string is \"%s\".\n", string);
 
   return 0;
}
 
void reverse(char *string) 
{
   int length, c;
   char *begin, *end, temp;
 
   length = string_length(string);
 
   begin = string;
   end = string;
 
   for ( c = 0 ; c < ( length - 1 ) ; c++ )
      end++;
 
   for ( c = 0 ; c < length/2 ; c++ ) 
   {        
      temp = *end;
      *end = *begin;
      *begin = temp;
 
      begin++;
      end--;
   }
}
 
int string_length(char *pointer)
{
   int c = 0;
 
   while( *(pointer+c) != '\0' )
      c++;
 
   return c;
}

C program to reverse a string using recursion

#include<stdio.h>
#include<string.h>
 
void reverse(char*,int,int);
 
main()
{
   char a[100];
 
   gets(a);
 
   reverse(a, 0, strlen(a)-1);
 
   printf("%s\n",a);
 
   return 0;
}
 
void reverse(char *x, int beg, int end)
{
   char a, b, c;
 
   if ( beg >= end )
      return;   
 
   c = *(x+beg);
   *(x+beg) = *(x+end);
   *(x+end) = c;
 
   reverse(x, ++beg, --end);
}
Reverse string program executable.
Output of program:
reverse string

0 comments:

Post a Comment