Reverse String Program in C

 /*Program to Reverse String*/  
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<string.h>  
 void main()  
 {  
      char str[20];  
      char rev[20];  
      long len;  
      int i,j;  
      printf("\n Please enter any string of length:");  
      scanf("%20s",str);  
      printf("\n String entered is:%s",str);  
      len = strlen(str);  
      printf("\n Method1: Reverse String:");  
      for(i =len-1,j=0; i>=0;i--,j++)  
            rev[j]=str[i];  
            rev[j]='\0';  
      printf("%s\n",rev);  
      i = 0;  
      j = len-1;  
      Printf("\n Method2: Optimized way of Reversing String: ");  
     while(i < j)  
     {  
            str[0] = rev[j];  
            rev[j] = rev[i];  
            rev[i] = str[0];  
        i++;  
        j--;  
     }  
     printf("\n Original String is:%s\n", rev);  
 }  

2 comments:

  1. This tutorial is very useful...

    ReplyDelete
  2. C++ Program to Reverse a Strings

    Reverse a String means reverse the position of all character of String. You can use swapping concept to reverse any string in c++.

    ReplyDelete