Tuesday, June 19, 2012

C program to reverse a string !!

Below is the complete working example for string reverse fuction in C programming language.
#include<stdio.h>
#include<string.h>
//strrev function using arrays
void str_rev_arry(char *str)
{
 int len = strlen(str);
 int i=0,j=len-1;
 for(i=0;i<len/2;i++,j--)
 {
 char temp = str[i];
 str[i] = str[j];
 str[j] = temp;
 }
}
//strrev function using pointers
void str_rev_ptr(char *str)
{
 int len = strlen(str);
 int i;
 char *begin, *end;
 begin = str;
 end = str+len-1;
 for(i=0;i<len/2;i++)
 {
 char temp = *begin;
 *begin = *end;;
 *end = temp;
 begin++;
 end--;
 }
}
//strrev function using recursion
void str_rev_rec(char *str, int begin, int end)
{
 char temp;
 if(begin>=end)
 return;
 temp = *(str+begin);
 *(str+begin) = *(str+end);
 *(str+end) = temp;
 str_rev_rec(str, ++begin, --end);
}
main()
{
 char str[]="Hello string";
 int len,begin,end,choice;
 printf("Enter the String which is to be reversed\n");
 printf("1. Using Arrays\n2. Using Pointers\n3. Using Recursion\n4. Exit\n");
 printf("Enter the method choice\n");
 scanf("%d",&choice);
 switch(choice)
 {
 case 1:
 printf("before reverse the string is '%s'\n",str);
 str_rev_arry(str);
 printf("after reverse the string is '%s'\n",str);
 break;
 case 2:
 printf("before reverse the string is '%s'\n",str);
 str_rev_ptr(str);
 printf("after reverse the string is '%s'\n",str);
 break;
 case 3:
 len = strlen(str);
 begin = 0;
 end = len-1;
 printf("before reverse the string is '%s'\n",str);
 str_rev_rec(str,begin,end);
 printf("after reverse the string is '%s'\n",str);
 break;
 default:
 printf("wrong choice\n");
 break;
 }
}

No comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

AltStyle によって変換されたページ (->オリジナル) /